0

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 toggle among 8 classes. I tried to select previous class like strClass=$("#"+styleTarget[class*='border']), but it failed.

Will "toggle" help me in this?

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I really like the modulus. it is such a simple technique for something I have been over-coding for years. I love learning something new (even if it is old to some). Thank you.
0

You could find class with selector and then use .html to rewrite class name

Comments

0

I never tried using toggle with classes, what always worked for me is:

$("#element").addClass("some_class");
$("#element").removeClass("some_class");

Comments

0

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.