Haradzieniec
Haradzieniec

Reputation: 9338

Should hasClass precede removeClass - pure Javascript

To remove the class, I use

getElementsByClassName("myclass1")[i].classList.remove("myclass2")

based on HTML5 Techniques. (I know that's not for IE9-, that's for browsers only).

As far as I know it is absolutely fine do not check if class exists. Right?

However, in my case there are many items with myclass1 on the page where I want to remove myclass2, but most of them (let's say 90%) do not have myclass2.

Will checking if the class myclass2 exists will help to increase the performance as checking if exists could be much faster than delete? (still not sure about my last statement)

What would you do in my case?

Thank you.

Upvotes: 0

Views: 170

Answers (2)

talemyn
talemyn

Reputation: 7960

getElementsByClassName supports multiple classes, so if you want to streamline it, you can include both "myclass1" and "myclass2" in as parameters and it will return only those elements that have both (see here for more info: https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName).

So, in your case, I would recommend using this:

getElementsByClassName("myclass1 myclass2")[i].classList.remove("myclass2")

Upvotes: 1

Bergi
Bergi

Reputation: 665040

As far as I know it is absolutely fine do not check if class exists. Right?

Yes. remove does only remove the tokens it finds.

Will checking if the class myclass2 exists will help to increase the performance as checking if exists could be much faster than delete?

Hardly, because it would be searched twice in the list.

Upvotes: 1

Related Questions