I’m iterating over a large number of dom elements in Javascript, and I’d like to add/remove classes as appropriate.
What’s the most efficient add/remove class operation I can use?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Remove
The fastest reliable way (small/medium size):
If you know for sure that the string does not contain multiple occurrences of the same class name, you can better use the
string.replacemethod (any size):The other alternatives:
indexOfto find the position, and use string concatenation (substring) to remove the class (repeat this in a loop to remove all possible duplicates).Slowest for large strings with repetition, not slow neither fast in other cases.
Add (without doubt):