js find object in nodeList?

爱⌒轻易说出口 提交于 2019-12-06 21:35:53

问题


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.


回答1:


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.




回答2:


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)



回答3:


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.



来源:https://stackoverflow.com/questions/12980527/js-find-object-in-nodelist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!