Skip to content Skip to sidebar Skip to footer

How To Convert Array Of Live Dom Elements Into Live Nodelist?

For example I have this array object: Object [object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement] and I need to change it to a kind of va

Solution 1:

You've misunderstood what 'live' means in the context of a NodeList.

Live NodeLists are variable length. They might contain 3 nodes one minute and 17 nodes the next. As you access and iterate over the NodeList the child/parent/sibling relationships are reevaluated to decide which nodes the NodeList should contain.

You cannot convert an arbitrary set of elements into a 'live' NodeList. It's just an arbitrary set of elements.

Excerpt from Mozilla docs for getElementsByTagName:

Returns a NodeList of elements with the given tag name. The complete document is searched, including the root node. The returned NodeList is live, meaning that it updates itself automatically to stay in sync with the DOM tree without having to call document.getElementsByTagName again.

Solution 2:

For browsers that support getElementsByClassName, you can assign an otherwise unrelated group of elements a class name and collect them in a node list with document.getElementsByClassName(grouping-class).

It will keep track of new elements added (with the same class name) and those that are removed from the document.

Post a Comment for "How To Convert Array Of Live Dom Elements Into Live Nodelist?"