selector - Check id and class using jQuery -
i've tried check id jquery, , i'm wondering why doesn't work. did wrong?
<td class="food" id="butter"> butter </td> <td class="food" id="milk"> milk </td> $(function(){ if ($('.food').attr('id') == "butter"){ $('.food').css({ color: 'red' }); } else { $('.food').css({ color: 'blue' }); } }); it shows red. ideas? thank much.
firstly there multiple .food elements, need loop using each(), , within loop need use this reference current element. try this:
$('.food').each(function() { if (this.id == "butter"){ $(this).css({ color: 'red' }); } else { $(this).css({ color: 'blue' }); } }); you can shorten further use of ternary:
$('.food').each(function() { $(this).css('color', this.id == 'butter' ? 'red' : 'blue'); });
Comments
Post a Comment