Kevin Lloyd Bernal
Kevin Lloyd Bernal

Reputation: 363

javascript retrieve class names from multiple elements

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!

Upvotes: 1

Views: 92

Answers (3)

Gurminder Singh
Gurminder Singh

Reputation: 1755

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 */
   }

});

Upvotes: 2

Manish Goyal
Manish Goyal

Reputation: 700

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

  }
});

Upvotes: 0

Pointy
Pointy

Reputation: 413996

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) {
  // ...

Upvotes: 1

Related Questions