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?

Link to comment
Share on other sites

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>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.