The use of :scope within querySelector querySelectorAll selector strings

6 hours ago 2
ARTICLE AD BOX

:scope will set the starting point of the selector to the element on which querySelector was called. Without it, the selector will start at the root and will look for elements higher up in the DOM. If you are used to CSS nesting, then it's about the same as the & selector, (which can be used too btw):

const source = document.getElementById("source"); const test = (selector) => console.log(`${selector}:`, source.querySelector(selector)); test("body span"); // <span></span> test(":scope body span"); // null test("body :scope span"); // <span></span> test("& body span"); // null test("body & span"); // <span></span> test(":scope span:is(body *)"); // <span></span> <div id="source"> <span></span> </div>

However, the use of :scope doesn't in itself mean that the engine won't have to look up from the root of the document. As demonstrated in the example above, it can be placed anywhere in the selector, and you can even have :is() pseudo-class in the selector that would make a look back the tree.

As to whether that selector adds or remove work in case the result would be the same, that would probably depend on the engine, but I'd expect it to have no noticeable difference in most.

Kaiido's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article