Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 599
Get Off My Lawn Avatar asked Feb 27 '18 16:02

Get Off My Lawn


1 Answers

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>
like image 150
Quentin Avatar answered Nov 12 '22 21:11

Quentin