【问题标题】:querySelector :scope is null查询选择器:范围为空
【发布时间】:2018-02-28 00:14:12
【问题描述】:

我正在尝试选择当前元素的同级元素,但是当我在元素上使用 a.querySelector(':scope') 时,它为空。当我尝试向:scope 添加同级选择器时,它仍然为空,但如果我在.matches(':scope') 中使用它,它会返回true。如何在选择器中使用当前元素?

let a = document.querySelector('div > a')
console.log(a.querySelector(':scope'))
console.log(a.querySelector(':scope + span'))
console.log(a.matches(':scope'))
<div>
  <a href=""></a>
  <span></span>
</div>

【问题讨论】:

  • .querySelector() "返回第一个元素,它是调用它的元素的后代":scope 是元素 .querySelector() 已被调用。这两个组合 -> a.querySelector(':scope') 返回 null 因为 a 不是 a 的孩子

标签: javascript css-selectors


【解决方案1】:

querySelector 选择上下文元素的后代

元素本身不会是它自己的后代,它的任何兄弟也不会。

如果您要定位后代,则可以使用:scope

例如,要仅搜索 children 而不是更深的后代,您可以将 :scope 与 child 组合器一起使用。

let a = document.querySelector('#foo')
console.log(a.querySelector(':scope > span'))
<div id="foo">
 <div><span>2</span></div>
 <span>1</span>
</div>

【讨论】:

  • 值得补充的是 :scope 伪类本身被设计为像 querySelector 一样工作,范围选择器只匹配 :scope 的后代(范围根),所以像 :scope + span 这样的选择器,而有效,永远不会匹配任何东西,无论它在哪里使用(即即使在 querySelector 以外的地方)。
  • 谷歌搜索 js queryselector scope sibling 把我带到这里,@BoltClock 评论正是我想要的。
猜你喜欢
  • 2013-09-21
  • 1970-01-01
  • 2017-08-07
  • 1970-01-01
  • 1970-01-01
  • 2019-04-10
  • 1970-01-01
  • 1970-01-01
  • 2018-03-08
相关资源
最近更新 更多