Joseph777
Joseph777

Reputation: 21

How do I add odd/even class only for table rows which haven´t had odd/even class yet?

How do I add odd/even class only for table rows which haven´t had odd/even class yet? (for some tables I use PHP cycle function).

Is this correct?

$("table tbody tr td")
  .parent("tr:nth-child(odd):not(.odd)")
  .addClass("odd")
  .end()
  .parent("tr:nth-child(even):not(.even)")
  .addClass("even");

Upvotes: 0

Views: 5298

Answers (2)

Umanda
Umanda

Reputation: 4843

Why can not use as follows?

$("table tbody tr:odd").addClass("odd");
$("table tbody tr:even").addClass("even");

Upvotes: 0

Terry
Terry

Reputation: 66123

jQuery will not duplicate the class if it has already been defined. You can of course always check using .hasClass() but it is not necessary in this scenario.

Try:

$("table tbody tr:nth-child(odd)").addClass("odd");
$("table tbody tr:nth-child(even)").addClass("even");

[Edit]: From your question is seems that some, but not all, rows have the "odd" or "even" classes already added to them. The safest way is to strip all classes and add them back using JS - $("table tbody tr").removeClass("odd even")

Upvotes: 1

Related Questions