Reputation:
Here is my HTML
<span class="sp-right">
<label>Name:</label>
</span>
<span class="sp-left">
<select name="omoor" required>
<option value="" style="display:none">something</option>
</select>
</span>
I want to change sp-right
class to sp-left
class and sp-left
to sp-right
with toggle .
here is my jquery :
$(".sp-right").each(function(){
$(this).removeClass("sp-right").addClass("sp-left");
});
it's working only once and for 1 element ?
Any idea ?
Thanks
Upvotes: 1
Views: 311
Reputation: 193301
As simple as one line with toggleClass
:
$('.sp-right, .sp-left').toggleClass("sp-right sp-left");
No need to check for classes and remove/addClass manually, as toggleClass
does exactly this. You can also provide multiple space separated classes to toggle.
Upvotes: 4
Reputation: 27102
Check the current classname inside the function.
$(".sp-left, .sp-right").each(function(){
var el = $(this);
if (el.hasClass('sp-left')) {
el.removeClass("sp-left").addClass("sp-right");
} else {
el.removeClass("sp-right").addClass("sp-left");
}
});
Upvotes: 1