2 hours ago · Tech · hide · 0 comments

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…

No comments yet. Log in to reply on the Fediverse. Comments will appear here.