Reputation: 4302
I have four html elements that when clicked I want to have a specific class applied to. The problem is that that class is only for one of the four at any one time. I want to when one element is clicked have that class removed from the other three elements and applied to the one that was clicked. If I were to run a loop that removed that class from every single element before applying that class to the element clicked would there be an error on the elements that did not have that class?
Upvotes: 4
Views: 2437
Reputation: 15835
@chrome dude, no there won't be any problem. Jquery takes care of null check. If you have class it will do it otherwise it won't do it.
Upvotes: 7
Reputation: 532595
No. The removeClass()
function returns jQuery (the same jQuery object it was invoked on) and won't do anything if the class isn't present. You really only need to remove the class from the element that has it, though.
$('a').click( function() {
$('a.foo-class').removeClass('foo-class');
$(this).addClass('foo-class');
});
Upvotes: 4