Search code examples
javascriptobjectnodes

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.


Solution

  • I don't think there's a built-in DOM method for that. You'd need to recursively traverse your NodeList, and check for equality with your element. Another option is to use Element.querySelectorAll on each first-level elements from your NodeList (looking for your element's id, for example). I'm not sure how (inn)efficient that would be, though.