classList.remove is removing elements from a HTMLCollection?

Using document.getElementsByClassName returns a live HTMLCollection:

An HTMLCollection in the HTML DOM is live; it is automatically updated when the underlying document is changed.

Thus (as described in plalx's answer) if you remove an element's class, the element is removed from an HTMLCollection based on that class.

Instead you could use document.querySelectorAll which returns a static NodeList collection:

The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

So your code would change from

var elements = document.getElementsByClassName("testing");

with the class name "testing" as an argument, to

var elements = document.querySelectorAll(".testing");

with the class selector ".testing" as an argument.

And then you could iterate over elements which would be a static NodeList.


The collection returned by document.getElementsByClassName is live so if an element doesn't have that class anymore it will be removed from the collection.

You can either create a non-live copy of the collection:

var elements = [].slice.call(document.getElementsByClassName('testing'));

Or take in account that it's live:

while (elements.length) elements[0].classList.remove('element-focus');

Tags:

Javascript