Skip to content
Advertisement

My replace function works with array but not with HTML collection which is also an array. Why?

I am writting a function to replace the position of some HTML elements in the page. Should be simple and it goes like this :

JavaScript

It works with testArray but it doesn’t seem to have any effect on the HTML elements order. Why and what can I do to change the original DOM?

Advertisement

Answer

You need to clear the element’s current children then append them again.

JavaScript

document.getElementById("SquareCharts").children returns a HTMLCollection. Although it is iterable using a for-loop, it is not an Array.

You can also do:

JavaScript

so that you can get more functionality with Array‘s built-in methods.

Advertisement