Get Off My Lawn
Get Off My Lawn

Reputation: 36311

querySelector :scope is null

I am trying to select a sibling of the current element, but when I use a.querySelector(':scope') on the element it is null. When I try to add a sibling selector to the :scope it is still null, but if I use it within .matches(':scope') it returns true. How can I use the current element within the selector?

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>

Upvotes: 10

Views: 6662

Answers (1)

Quentin
Quentin

Reputation: 943605

querySelector selects the descendants of the context element.

The element itself won't be a descendant of itself, and nor will any of its siblings.

You can use :scope if you are targetting a descendant.

For example, to search only the children and not deeper descendants you can use :scope with the child combinator.

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

Upvotes: 11

Related Questions