Remove and add specific classes using jQuery
I need to remove existing class of an element and add another class...or shortly I want to replace a specific class having letters 'border' as substring by another class with letters 'border' as substring.
I have to开发者_JS百科 toggle among 8 classes. I tried to select previous class like strClass=$("#"+styleTarget[class*='border'])
, but it failed.
Will "toggle" help me in this?
You could do something like this:
var classes = ['border1', 'border2', 'border3', 'border4'];
$("div[class*='border']").click(function() {
for(var i=0; i<classes.length; i++) {
if($(this).hasClass(classes[i])) {
$(this).removeClass(classes[i]).addClass(classes[(i+1)%classes.length]);
break;
}
}
});
You can try it here, it'll work for any number of classes, just add as many as you want to cycle through. The concept is pretty straight-forward, when an element's clicked we loop through the array, if we find a class it has (via .hasClass()
), we remove it (via .removeClass()
) and give it the next class (via .addClass()
).
The (i+1)%classes.length
modulus is to handle wrapping around to the beginning of the array when it currently has the last class in it.
You could find class with selector and then use .html to rewrite class name
I never tried using toggle with classes, what always worked for me is:
$("#element").addClass("some_class");
$("#element").removeClass("some_class");
We could provide a better answer if you shared your code, but the .toggleClass() function will remove a class if it is currently used on the selected element or add it if it does not exist. And you can specify multiple classes to be removed or added, like so:
// removes or adds classes depending on existence
$('#element_id').toggleClass('one two three four');
精彩评论