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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With