简体   繁体   English

CSS 后代选择器获取具有特定属性的所有元素,忽略具有相同属性的元素的任何后代

[英]CSS descendent selector to get all elements with a certain attribute, ignoring any that are descendents of an element with that same attribute

I'm using element attributes to identify a tree-like structure in the DOM and each node that branches looks after its children.我正在使用元素属性来识别 DOM 中的树状结构,并且每个分支的节点都会照顾它的子节点。 It does so by searching descendents of the node in the DOM and checking for the attribute that identifies another node.它通过在 DOM 中搜索节点的后代并检查标识另一个节点的属性来做到这一点。 It needs to do this since the child nodes might be several layers deeper in the DOM.它需要这样做,因为子节点可能在 DOM 中更深几层。

I'm currently doing this with the following JS:我目前正在使用以下 JS 执行此操作:

const directChildNodes = [...nodeElement.querySelectorAll(`[tree-node-name="${this.treeName}"]`)]
  // filter all results where the current node is the closest parent
  .filter((el: Element) =>
    el.parentElement?.closest(`[tree-node-name="${this.treeName}"]`) === this.host.nativeElement);

This works, but is not very efficient as it grabs all elements with the attribute and then filters out ones that don't identify the current node as the closest parent.这可行,但效率不高,因为它会抓取具有该属性的所有元素,然后过滤掉那些不将当前节点标识为最近父节点的元素。 I would ideally be able to achieve this in the CSS selector.理想情况下,我可以在 CSS 选择器中实现这一点。

I've tried the following selector but this does not seem to work:我尝试了以下选择器,但这似乎不起作用:

nodeElement.querySelectorAll(
  `[tree-node-name="${this.treeName}"]:not([tree-node-name="${this.treeName}"] [tree-node-name="${this.treeName}"])`
)]

Any suggestions would be great, thanks任何建议都会很棒,谢谢

What about using the :scope pseudo class :使用:scope伪 class 怎么样

nodeElement.querySelectorAll(':scope > [tree-node-name="${this.treeName}"]')

It's not supported in IE but it's supported in most browsers . IE 不支持,但大多数浏览器都支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM