如何为根节点的直接 child 创建一个选择器?

How to make a selector for direct child of the root node?

考虑给你一个节点node,你必须提供select或Direct给出的所有直接children。直接 child 的选择器是:

childParent > directChild

但是,以下操作失败并在控制台中出现错误:

document.body.querySelectorAll(">div")
SyntaxError: '>div' is not a valid selector

我有一个函数需要在 select 直接 child 节点上执行某些操作,但我不确定如何处理它。当然除了使用 for 循环并用我自己的代码分析 children,完全放弃 selectors。

以下代码无效。是否可以对其进行更改以使其发挥预期作用?

function doWithDirectChildren(parentNode) {
    // does not work, the selector is invalid
    const children = parentNode.querySelector(">.shouldBeAffected");
    for(const direct of children) {
        // do something with the direct child
    }
}

我要求的是解决方案,而不是解决方法。

jQuery 以两种方式解决了这个问题。考虑这段代码:

$('div.root').find('> .p2').addClass('highlighted');
$('div.root').children('.p2').addClass('red');
.highlighted {
  background: yellow
}

.red {
  color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="root">
  <p>div 1</p>
  <p class="p2">paragraph 2</p>
  <p>paragraph 3</p>
  
  <div>
    <p class="p2">paragraph 2 2</p>
  </div>
</div>

使用 .find('> selector) 仅查找与选择器匹配的直接子项,使用 .children('selector') 也可以做到这一点。

child combinator 运算符 > 是一个二元运算符,因此在左侧没有任何内容的情况下使用它是无效的。

The child combinator (>) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the direct children of elements matched by the first.

如果您可以提供单独的 parentchild 选择器,您可以像这样简单地做一些事情

let directChildren = (parent, child) => document.querySelectorAll(`${parent} > ${child}`);
directChildren('body','div');//...

如果您的父参数是节点或集合,则必须使用一种方法将其转换回选择器,like this one

正确的方法是使用 :scope 伪 class.

根据 MDN 的 documentation

When used from a DOM API such as querySelector(), querySelectorAll(), matches(), or Element.closest(), :scope matches the element on which the method was called.

例如:

let parent = document.querySelector('#parent');
let scoped = parent.querySelectorAll(':scope > span');

Array.from(scoped).forEach(s => {
  s.classList.add('selected');
});
.selected {
  background: yellow;
}
<div id="parent">
  <span> Select Me </span> <br>
  <span> Me Too </span>
</div>
<span> Not Selected </span>