How to convert an array of dom live elements to a 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 some value that the getElementsByTagName method returns, but not moving nodes from node tree to my new node list, which is a live NodeList. My html elements in the ale array already live and point to the real elements on the page, therefore, for example, adding an event is reflected on the page.

+1
source share
2 answers

You misunderstood what "live" means in the context of NodeList.

Live NodeLists - variable length. They can contain 3 nodes in one minute and 17 nodes. When you access and iterate over the NodeList, the child / parent / sibling relationship is re-evaluated to determine which nodes the NodeList should contain.

You cannot convert an arbitrary set of elements to a live NodeList. This is just an arbitrary set of elements.

Excerpt from Mozilla docs for getElementsByTagName :

Returns the NodeList of the elements with the specified tag name. A search is complete for the document, including the root node. The returned NodeList is live, which means it is automatically updated to stay in sync with the DOM tree without having to say document.getElementsByTagName.

+2
source

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

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

+1
source

Source: https://habr.com/ru/post/955131/


All Articles