Backo
Backo

Reputation: 18871

Improving to class toggling

I am using jQuery 1.6 and I would like to improve the following code (that is, write less do more):

if (row.hasClass('line_odd')) {
  row.removeClass('line_odd');
  row.addClass('line_even');
} else {
  row.removeClass('line_even');
  row.addClass('line_odd');
}

How can I do that?

Upvotes: 0

Views: 103

Answers (6)

Piyush Mattoo
Piyush Mattoo

Reputation: 16125

row.toggleClass('line_odd', row.hasClass('line_odd') ).toggleClass('line_even', 
row.hasClass('line_odd') );

This is the reduced version which makes use of .toggleClass alongwith the second argument that when true adds the class and if false removes the class.

Upvotes: 0

coyotebush
coyotebush

Reputation: 653

Assuming row starts with exactly one of the two classes:

row.toggleClass("line_odd line_even")

should do the trick.

Upvotes: 1

JaredPar
JaredPar

Reputation: 754763

Try the following

var isOdd = row.hasClass('line_odd');
row.toggleClass('line_odd', !isOdd);
row.toggleClass('line_even', isOdd);

Upvotes: 1

Geoff Adams
Geoff Adams

Reputation: 1119

I would suggest use of something like http://api.jquery.com/toggleClass/, for example:

row.toggleClass("line_odd")
   .toggleClass("line_even");

This assumes that no row element would have both the line_odd and line_even classes set initially, in order for it to have the same effect as your code.

Upvotes: 2

Rafay
Rafay

Reputation: 31033

you can use chaining

if (row.hasClass('line_odd')) {
  row.removeClass('line_odd').addClass('line_even');

} else {
  row.removeClass('line_even').addClass('line_odd'); 
}

Upvotes: 0

Chandu
Chandu

Reputation: 82913

Replace the block with:

var hasOdd = row.hasClass('line_odd');
row.toggleClass('line_odd', !hasOdd).toggleClass('line_even', hasOdd);

Upvotes: 3

Related Questions