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'); }); 

working example


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -