Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

js find object in nodeList?

Fallback is irrelevant. No libraries, please.

We have an dom object reference, we'll call obj. It's actually an event.target.

We have a node list, we'll call nodes, which we've gotten with querySelectorAll and a variable selector.

nodes may have 1 or many elements, and each each of those elements may have children.

We need to determine if obj is one of those node elements, or children elements of those node elements. We're looking for "native" browser functionality here, we can totes write our own for loop and accomplish this, we are looking for alternatives.

Something like:

nodes.contains(obj) OR nodes.indexof(obj)

Solutions involving other methods of retrieving the node list to match against are acceptable, but I have no idea what those could be.

like image 574
Randy Hall Avatar asked Oct 19 '12 18:10

Randy Hall


People also ask

How do I get the elements of a NodeList?

const myNodeList = document. querySelectorAll("p"); The elements in the NodeList can be accessed by an index number.

What does a NodeList contain?

A NodeList is a collection of document nodes (element nodes, attribute nodes, and text nodes). HTMLCollection items can be accessed by their name, id, or index number. NodeList items can only be accessed by their index number. An HTMLCollection is always a live collection.

Does forEach work on NodeList?

forEach() The forEach() method of the NodeList interface calls the callback given in parameter once for each value pair in the list, in insertion order.

What is the difference between NodeList and array?

A NodeList may look like an array, but in reality, they both are two completely different things. A NodeList object is basically a collection of DOM nodes extracted from the HTML document. An array is a special data-type in JavaScript, that can store a collection of arbitrary elements.


2 Answers

If <=IE11 is not a concern then I think the cleanest is to use Array.from

Array.from(nodes).find(node => node.isEqualNode(nodeToFind));
like image 85
Dominic Avatar answered Sep 19 '22 14:09

Dominic


I'm not sure if this will search beyond the first level of the NodeList, but you can use this expression recursively to traverse it and check if the element 'obj' is in the NodeList 'nodes'.

[].indexOf.call(nodes, obj)
like image 44
KthProg Avatar answered Sep 16 '22 14:09

KthProg