Harshveer Singh
Harshveer Singh

Reputation: 4197

Visit each element in HTMLCollection/NodeList

I would like to visit each element (using only JavaScript, no jQuery or any other JavaScript library) in live HTMLCollection or NodeList, for example collection returned by var elements = document.getElementsByClassName('class-name');

If DOM is not changing then I can do this with for loop:

for(var i=0; i<elements.length; i++)
{
    //Do something with elements[i]
}

But what to do in situation when for loop is still running and there is addition or deletion of elements with class class-name. If an element has been deleted or added then indices will change.

So, how can I make sure that while for loop is running, no element in elements is missed using JavaScript only.

Upvotes: 1

Views: 406

Answers (3)

Esailija
Esailija

Reputation: 140236

The "live" collections are just really awkward default that keep surprising people. I suggest you simply use querySelectorAll which is not only more supported than gEBCN but returns a snapshot instead of a "live" collection.

I see that even the notion that the collection is "live" causes confusion. It is not live, but basically the properties are getters e.g. [i] actually calls .item(i) - the method dynamically then retrieves the element which makes the collection appear live.

And there's more. Some people keep using these methods because they wrongly think they are substantially faster due to broken benchmarks. In those benchmarks, only direct method calls are compared and it is not considered that "live" collections do not do any work until you try to retrieve the elements.

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382444

There's only one script running at a given time. The only changes that can happen to the DOM while your script is running are the ones made by your script. All other tasks, events, etc. will patiently wait for your script to finish execution.

So

  • don't worry for external changes to the DOM, there is none
  • track the changes your code made

and you'll be fine.

Upvotes: 3

Michiel Dral
Michiel Dral

Reputation: 4074

As far as I know the for loop is not asynchronous so the elements can't change, as the for loop gets fully executed before the change will happen d, or the change should happen before the for loop.

Upvotes: 0

Related Questions