querySelector immediate children with :scope
Some features of this website do not work as expected when JavaScript is disabled<br>Requirement<br>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?<br>Failed attempt<br>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...<br>Solution<br>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 element and is identical to the selector html, except that its specificity (0-1-0) is higher than html's (0-0-1).">:root.<br>: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.<br>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.<br>Hope that helps!
Share on Facebook Share on Twitter Email Comments<br>Be the first to post a comment<br>Post a comment
Comment Name E-mail
Enable JavaScript to post comments on this blog.