CSS selectors with querySelector: Select only top level element(s) in shadow DOM

2 days ago 2
ARTICLE AD BOX

Assuming the following HTML content

<template> <div> an amount of unknown content may contain: <div TAG>undesired node</div> </div> At the root level: <div TAG>desired node</div> </template>

I wish to, in JavaScript, select the root level node with TAG.
The following are statements I could come up with:

tem.content.querySelectorAll("[TAG]") // => [div, div] // includes non-root tem.content.querySelectorAll("> [TAG]") // => Error // invalid syntax tem.content.querySelectorAll(":root") // => [] // no :root tem.content.querySelectorAll(":host") // => [] // no :host tem.content.querySelectorAll(":host([TAG])") // no :host tem.content.querySelectorAll(":scope") // => [] // no :scope

None of the above return the desired elements.
Filtering the results of the former is possible but it feels like that work is unnecessary.
What would, if there is one, the correct statement be?
Thank you

// (Workaround in the meantime) [...tem.content.querySelectorAll("[TAG]")].filter(e => e.parentNode instanceof DocumentFragment) // => [div] // desired outcome

Example:

function print(test) { console.log(`Running: ${test}`); try { for (const result of test()) console.log("Result: " + result.outerHTML); } catch {} } const tem = document.getElementById("tem") print(() => tem.content.querySelectorAll("[TAG]")) // => [div, div] print(() => tem.content.querySelectorAll("> [TAG]")) // => Error print(() => tem.content.querySelectorAll(":root")) // => [] print(() => tem.content.querySelectorAll(":host")) // => [] print(() => tem.content.querySelectorAll(":host([TAG])")) // => [] print(() => tem.content.querySelectorAll(":scope")) // => [] print(() => [...tem.content.querySelectorAll("[TAG]")].filter(e => e.parentNode instanceof DocumentFragment)) // => [div] <template id="tem"> <div> an amount of unknown content may contain: <div TAG>undesired node</div> </div> At the root level: <div TAG>desired node</div> </template>
Read Entire Article