views:

82

answers:

1

I have following code where commentTable is the class. It works fine for current comments displayed on the page.

$(".commentTable:odd").addClass("commentTableClass1"); $(".commentTable:even").addClass("commentTableClass2");

but what I really want is that this addition of class be 'live' even when new comments are added. I don't want to remove class and re-add them to get the effect. I just want to apply to new innerHTML the "correct" class.

I could keep count of number of comments and apply different class but I wanted something elegant.

+1  A: 

You could put them in a function and call the function each time...

function oddEven(){
   $('.commentTable').removeClass('commentTableClass1').removeClass('commentTableClass2');
   $(".commentTable:odd").addClass("commentTableClass1");   
   $(".commentTable:even").addClass("commentTableClass2");
}

then you can just call oddEven(); rather than removeClass and addClass. It's cleaner. I wouldn't exactly call it elegant though.

OR

this would probably be faster and more what you're looking for:

function getCommentClass(){
   var newClass;
   if($('.comment').length % 2 == 0){
      //there's an even number already, the new one will be odd
      newClass = 'commentTableClass2';
   }else{
     //new one will be even
      newClass = 'commentTableClass1';
   }

   return newClass;
}

var commentClass = getCommentClass();
$('#newElement').addClass(commentClass);

Either way, though, you'd need to call a function each time you load a new comment.

munch
Great. I like the second solution!
Shailesh