简体   繁体   中英

Add class to element that doesn't have class - jQuery

In the table below only one td has class, another doesn't have class like:

<table id="bow-me">
  <tr class="row-me">
    <td class="show-me">Pet is Great</td>
    <td>Pete is Greate</td>
  </tr>
</table>

I tried something like:

if(!$("#bow-me tr td").hasClass("show-me")) {
  $(this).addClass("know-me");
}

But this doesn't add the class know-me in my second td here.

I have attached the JSFiddle here

If I want to add Class to the second td only then how do I do?

Try attribute selector and :not() to get the <td> without any class

$('#bow-me tr td:not([class])').addClass('know-me');

Or if you want to specify which <td> like first or second, use :eq()

$('#bow-me tr td:eq(1)').addClass('know-me');

Doc reference

  1. :not()
  2. Attribute selectors
  3. .eq()

You can use :eq() selector:

$('#bow-me tr.row-me td:eq(1)').addClass('know-me');

Updated Fiddle

or .eq()

$('#bow-me tr.row-me td').eq(1).addClass('know-me');

Updated Fiddle

the reason your code doesn't work is because

  1. There are multiple td 's found with your selector

    $("#bow-me tr td")

  2. You can't use the $(this) as a selector inside your if conditional statement. it has no valid reference as is.

Solution: you can cycle through the matched elements via each() function and then set up your conditional to check each one of the elements found - $(this) would work in this case

$("#bow-me tr td").each(function() {
  if(! $(this).hasClass("show-me")) {
    $(this).addClass("know-me");
  }
});

check out the jsFiddle here

I gave this answer as an explaination as to why your approach does not work. I prefer Anton's approach that uses the :not() pseudo selector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM