javascript - 为什么 'document.querySelectorAll' 只针对直系 child ?

标签 javascript html css dom

根据MDN page对于 document.querySelectorAll , 语法是

elementList = document.querySelectorAll(selectors);

在哪里

*selectors* is a string containing one or more CSS selectors separated by commas

但这似乎不适用于通配符子选择器。考虑以下 HTML

<div id="container">
  <p>One <a href="#">Link One</a> </p>
  <p>Two <a href="#">Link Two</a> </p>
  <p>Three <a href="#">Link Three</a> </p>

  <a href=#>Outer Link One</a>
  <a href=#>Outer Link Two</a>
  <a href=#>Outer Link Three</a>
</div>

用下面的JS

[].forEach.call(document.querySelectorAll('#container *:not(a)'), 
function(node) {
  node.style.fontWeight = 'bold';
});

和下面的 CSS

#container {
  border: 1px solid #888;
  border-radius: 5px;
  padding: 10px;
}

#container *:not(a) {
  color: green;
}

你会看到 css *:not(a)从样式中排除所有 anchor 标记,而在 JS 中使用的相同选择器似乎只排除作为 #container 的直接子级的 anchor 标记, 就好像它是 #container > a

为什么会这样?有没有办法获得与 querySelectorAll 中的 CSS 相同的结果?方法?

JS Fiddle

最佳答案

Why does 'document.querySelectorAll' only target immediate children?

它不会,它会查找所有后代。

您正在使包含 a 元素的 p 元素变为粗体,并且 a 元素继承了它;而 a 元素有自己的颜色。如果您颠倒粗体和颜色,以便 CSS 应用粗体而 JavaScript 应用颜色,您将看到 querySelectorAll 正在做与 CSS 正在做的相同的事情:

[].forEach.call(document.querySelectorAll('#container *:not(a)'), 
function(node) {
  node.style.color = "green";
});
#container {
  border: 1px solid #888;
  border-radius: 5px;
  padding: 10px;
}

#container *:not(a) {
  font-weight: bold;
}
<div id="container">
  <p>One <a href="#">Link One</a> </p>
  <p>Two <a href="#">Link Two</a> </p>
  <p>Three <a href="#">Link Three</a> </p>

  <a href=#>Outer Link One</a>
  <a href=#>Outer Link Two</a>
  <a href=#>Outer Link Three</a>
</div>

And is there a way to get the same result as the CSS in the querySelectorAll method?

CSS 和 querySelectorAll 已经解决了相同的元素。 :-) 如果你不想让 a 元素变成粗体,你必须告诉他们不要从他们的祖先那里继承:

#container a {
  font-weight: normal;
}

例子:

[].forEach.call(document.querySelectorAll('#container *:not(a)'), 
function(node) {
  node.style.fontWeight = "bold";
});
#container {
  border: 1px solid #888;
  border-radius: 5px;
  padding: 10px;
}

#container *:not(a) {
  color: green;
}
#container a {
  font-weight: normal;
}
<div id="container">
  <p>One <a href="#">Link One</a> </p>
  <p>Two <a href="#">Link Two</a> </p>
  <p>Three <a href="#">Link Three</a> </p>

  <a href=#>Outer Link One</a>
  <a href=#>Outer Link Two</a>
  <a href=#>Outer Link Three</a>
</div>

关于javascript - 为什么 'document.querySelectorAll' 只针对直系 child ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43315681/

相关文章:

javascript - Bootstrap 网格类用法

html - 如何在 div 上创建垂直居中的 session 边框?

html - "full-size"绝对定位方式的区别

javascript - 使用 javascript setTimeout() 设置 z-index

javascript - 使用 CasperJS 从 querySelectorAll 遍历 NodeList

javascript - CheckBox 禁用属性绑定(bind)到 Polymer Property 的子属性

jquery - 如何使内容适合浏览高度

javascript - 仅当在输入字段 ANGULARJS 中键入文本时才发出 http get 请求

javascript - 我可以像这样按顺序选课吗?

javascript - 选择相同宽度的选项