Question

In Javascript, I get the elements of a given class using:

A = document.getElementsByClassName("someclass");
> A contains elements e1, e2, e3, e4

Then, I change the class of one of these elements:

document.getElementById("e2").className = "anotherclass";

To my great surprise, the array A has been automatically changed in the process !!

> A contains elements e1, e3, e4

I thought that the array returned by getElementsByClassName would stay the same now that is was assigned.

  • How is that possible? Is it an intended behaviour?
  • Is there a simple way to change that?

Here is a JSfiddle.

Note that this is also true for getElementById.

Was it helpful?

Solution

This is because A is not an Array. getElementByClassName returns an HTMLCollection which is live-updated due to changes in the document.

The easiest way to convert an array-like object into an array would be to do this:

var A = ...

// With ES5 code
var A_array = Array.prototype.slice.call(A);

// With ES6 code
var A_array = Array.from(A);

Or you can get NodeList instead via querySelectorAll, which won't live-update.

var A = document.querySelectorAll('.someclass');

OTHER TIPS

These functions return live NodeLists. This means that they are automatically updated to reflect the current contents of the DOM.

See the NodeList documentation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top