Jump to content

Jquery change css property - shouldn't this work?


V

Recommended Posts

After reading some Jquery documentation I tried to implement something for my site. If a link's "id" and "name" have equal values the background color of the link's class should change to green otherwise red.

 

<script type="text/javascript">
$(function() {

var ID = $(".color_test").attr("id");
var name = $(".color_test").attr("name");

if (ID==name)
{
$('.color_test').css({"background":"green"});
}

if (ID!==name)
{
$('.color_test').css({"background":"red"});
}

});
</script>

 

 

The HTML is dynamic but I made a simple example

 

 

<a href class="color_test" id="1" name="1">Should be green</a>

<a href class="color_test" id="3" name="4">Should be red</a>

<a href class="color_test" id="8" name="8">Should be green</a>

 

and the css

 

.color_test {
display:block;
padding:10px;
}

 

What happens is.. if "id" and "name" in the first link are equal, all the links become green even if some don't have equal values.  :-\ And so if the first link doesn't have equal values they all become red. It seems that it's just picking up the data from the first link rather than each one individually.

 

Can someone please help me out with this?

You'll need to iterate through all elements with the class name  of color_test

        <script type="text/javascript">
            $(function() {
                $('.color_test').each(function(i) {
                if($(this).attr("id") == $(this).attr("name"))
                    $(this).css({"background-color":"green"});
                else
                    $(this).css({"background-color":"red"});
            });
            });
        </script>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.