0

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?

3
  • just for clarity. an if block will not define 'this'. Commented Mar 7, 2014 at 12:21
  • do you mean in if() block if I define $('#id') then I cannot do $(this) in jQuery? this in JavaScript is really confusing Commented Mar 7, 2014 at 12:31
  • if() is just a condition and does not define the this keyword. you can use $(this) in an if() block but it will not reference the conditional value. Commented Mar 7, 2014 at 12:37

3 Answers 3

3

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()
Sign up to request clarification or add additional context in comments.

2 Comments

+1 Nicely selected with the first example, can't get any shorter than that!
Instead of knowing the eq(n) I think :not() is perfect for most solutions. Thanks
0

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

Comments

0

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.

1 Comment

Thank you for you answer, it is informative, I learned something new in JavaScript today.