Randy Hall
Randy Hall

Reputation: 8127

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.

Upvotes: 26

Views: 37913

Answers (6)

aljgom
aljgom

Reputation: 9129

You can convert the NodeList to an Array to then use Array.includes() to determine whether it includes the targetNode among its entries

[...nodes].includes(targetNode)

Upvotes: 4

nanobar
nanobar

Reputation: 66315

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

Array.from(nodes).find(node => node.isEqualNode(nodeToFind));

Upvotes: 24

DarkTrick
DarkTrick

Reputation: 3447

In addition to Dominic's answer as function:

function nodelist_contains (nodelist, obj)
{
  if (-1 < Array.from (nodelist).indexOf (obj))
    return true;
  
  return false;
} 

Upvotes: 0

Matt Goo
Matt Goo

Reputation: 1136

I did something like this:

Array.prototype.find.call(style.childNodes, function(child) {
  if(child.textContent.includes(drawer.id)) {
    console.log(child);
  }
});

Seems to work. Then child is another html node, which you can manipulate however you like.

Upvotes: 7

KthProg
KthProg

Reputation: 2117

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)

Upvotes: 15

bfavaretto
bfavaretto

Reputation: 71908

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.

Upvotes: 7

Related Questions