querySelector immediate children with :scope
Requirement
You are on a web page, using JavaScript, and have a reference to an element node. And you want to select the immediate children of that node using the general syntax used by querySelectorAll, maybe with some extra constraints. What do you do?
Failed attempt
The CSS syntax for children of a node is using the greater-than character, something like this: #parentNode > *, but as soon as you try in JavaScript parentNode.querySelectorAll('> *') you get an error: '> *' is not a valid selector.. That doesn't work...
Solution
The solution is using the :scope pseudo-class. In a "traditional" selector, it represents the element the method is called from, in our case #parentNode. The code becomes parentNode.querySelectorAll(':scope > *') and now it all works. In simple CSS it makes no sense as it just works exactly like :root.
:scope is widely supported in this particular scenario, since Chrome 27 and Firefox 32 and Safari 7, meaning it was completely supported at the end of 2014.
But it also has a secondary use, as a stand-in for the scoped element in the @scope CSS at-rule, which is something newly available in 2025 and frankly, pretty sweet. You can follow the documentation and even use it in your web sites made for modern browsers, but that's not in the... scope... of this blog post, though.
Hope that helps!
Comments
Be the first to post a comment