1

I have this in my page:

 <div id="container">

        <div>
            <p>...</p>
            <a href="#" class></a>
        </div>  

        <div>
            <p>...</p>
            <a href="#" class="checked"></a>
        </div>  

        <div>
            <p>...</p>
            <a href="#" class></a>
        </div>  

</div>

Now, I want some codes to execute when each of the a elements changes its class. This doesn't work:

$('#food_container').click( function() {

    if ($('#food_container a').attr('class') == "checked") {
        /* some codes */
    }

});

How to fix this? Thanks!

2
  • 1
    Do you mean that you want to check when any element has the class, or when all of them do? Commented Sep 28, 2013 at 16:36
  • 2
    Use .hasClass('checked') to check if the element has the class. Commented Sep 28, 2013 at 16:37

3 Answers 3

2

You are using wrong id in the selector. Change

$('#food_container').click( function() {

   if ($('#food_container a').attr('class') == "checked") {
    /* some codes */
   }

});

to

$('#container').click( function() {

   if ($('#container a').hasClass('checked')) {
    /* some codes */
   }

});
Sign up to request clarification or add additional context in comments.

1 Comment

What if the element has two classes? Checking the "class" attribute directly is usually not a good idea.
1

You can use .hasClass() to see if any of the elements have the class:

if ($('#container a').hasClass('checked')) {
  // ...

To see if all of them have the class:

if ($('#container a').length =  $('#container a.checked').length) {
  // ...

Comments

0
var links = $("#container").children("a");
$(links).each(function(i,v){
  if($(this).hasClass("checked")){

  }
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.