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.
const myNodeList = document. querySelectorAll("p"); The elements in the NodeList can be accessed by an index number.
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.
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.
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.
If <=IE11 is not a concern then I think the cleanest is to use Array.from
Array.from(nodes).find(node => node.isEqualNode(nodeToFind));
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With