Reputation: 18871
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
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
Reputation: 653
Assuming row starts with exactly one of the two classes:
row.toggleClass("line_odd line_even")
should do the trick.
Upvotes: 1
Reputation: 754763
Try the following
var isOdd = row.hasClass('line_odd');
row.toggleClass('line_odd', !isOdd);
row.toggleClass('line_even', isOdd);
Upvotes: 1
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
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
Reputation: 82913
Replace the block with:
var hasOdd = row.hasClass('line_odd');
row.toggleClass('line_odd', !hasOdd).toggleClass('line_even', hasOdd);
Upvotes: 3