Preciel
Preciel

Reputation: 2827

.forEach() stops after first iteration

A simple .forEach() stop after first iteration depending on the content...

My initial loop looked like this :

document.getElementsByClassName("app-form-to-js").forEach(function(node) {
    node.classList.remove("app-form-to-js");
    jsForms[node.id]=node.cloneNode(true);
    node.remove();
});

While the first loop occur, it doesn't go beyond.
Then, after some tweaking, I managed to get the loop working with this code :

document.getElementsByClassName("app-form-to-js").forEach(function(node) {
    jsForms[node.id]=node.cloneNode(true);
    jsForms[node.id].classList.remove("app-form-to-js");
});

But, the moment I use node.classList.remove("app-form-to-js"); or node.remove(); in the loop,
it will always stop after first iteration.

Any idea why loop is stopping after first iteration (so it iterate at least once) if I alter the node?

Upvotes: 2

Views: 1548

Answers (2)

Jesse
Jesse

Reputation: 1425

document.getElementsByClassName returns an HTMLCollection, which doesn't have a definition for forEach. You can however turn this into an array, which does have one defined, by using Array.from() like so:

var collection = Array.from(document.getElementsByClassName("app-form-to-js"));
collection.forEach(function(node){...});

EDIT:

As was pointed out to me by @Preciel, the NodeList object does have a forEach() function similar to an array. If you would rather use this, you can replace document.getElementsByClassName("app-form-to-js") with document.querySelectorAll(".app-form-to-js") and this will return a NodeList rather than an HTMLCollection

Upvotes: 4

Alex L
Alex L

Reputation: 4241

An alternative way to create an array using ES6 spread operator (this is my preferred method):

const elements = [...document.getElementsByClassName("app-form-to-js")];
elements.forEach((node)=>{...});
//OR:
elements.map((node,i)=>{... return node});
//Etc...

If you use the .map() method, you can make changes directly to the elements and it will be reflected in the DOM etc. - very powerful technique (remember to return the modified node in the function)

Upvotes: 0

Related Questions