tags:

views:

40

answers:

3

I have a table cell in the footer that allows the user to turn on row coloring:

$('#highlight').click(function() {
$(this).parents('table').RowColors();
})

// From Chapter 7 of Learning jQuery
$.fn.RowColors = function() {
$('tbody tr:odd', this).removeClass('even').addClass('odd');
$('tbody tr:even', this).removeClass('odd').addClass('even');
return this;
};

Q: How do I write a selector that says: IF there is at least 1 row with class="even", then remove both "even" and "odd" ELSE execute the RowColors function.

+5  A: 

My advice would be to do it slightly differently. Have just one class with the default state being the other. So:

tr td { background: yellow; }
tr.odd td { background: blue; }

and then this is as simple as:

$("tr").toggleClass("odd");

or more specifically:

$("tbody > tr").removeClass("odd").filter(":nth-child(odd)").addClass("odd");

Note: avoid using :odd and :even. They usually don't mean what you think they mean. :nth-child(odd) and :nth-child(even) tend to be what you really mean.

I would probably write something like:

$("#highlight").click(function() {
  $(this).closest("table").children("tbody").children("tr").removeClass("odd")
    .filter(":nth-child(odd)").addClass("odd");
  return false;
});

Put it into a separate function if you wish.

Edit: to check whether something is empty:

var odd = $(".odd");
if (odd.length == 0) {
  // do one thing
} else {
  // do something else
}

jQuery objects support the length property and the size() method, which do the same thing.

cletus
Cletus: I like where this is going. I need to be able to toggle the highlighting, such that if there is already a tr class="odd", then removeClass odd, else addClass odd.
cf_PhillipSenn
Oh I see where I'm not communicating correctly. What I mean by toggle is that there is no styling, or the odd rows are styled.
cf_PhillipSenn
How do you write an IF/THEN statement in JavaScript and jQuery?If I have a selector such as $('.odd'), and it returns _something_, then how do I check to see that it returned _something_, and not _nothing_?
cf_PhillipSenn
+1  A: 

Alternating row colors can be done with pure CSS (as long as you don't need to support IE6/7):

tr { background-color: green; }
tr:nth-child(even) { background-color: red; }
RoToRa
"as long as you don't need to support IE6/7" ...is there ANYBODY that lucky?
Chad
+1  A: 

There is a jQuery plug-in called Colorize that already does this. You could use it, or check out the code?

Dan Diplo