:scope Matches Nothing When You Query a DocumentFragment or Shadow Root

You want only the top-level rows of a <template>, not the rows of the tables nested inside it. On an element you'd write :scope > tr, so you try the same thing on the template's content:

const template = document.querySelector('#rows');

template.content.querySelectorAll(':scope > tr');  // NodeList []
template.content.querySelectorAll('tr');           // NodeList(5) [tr, tr, tr, tr, tr]

The rows are there, but :scope matches nothing. The same happens on a DocumentFragment you build yourself and on a shadow root.

Short answer: browsers only let :scope match an element. A fragment, template.content and a ShadowRoot aren't elements, so :scope matches nothing, and every selector that uses it returns an empty list. Select "elements with no parent element" instead:

template.content.querySelectorAll(':not(* > *)');      // top-level elements
template.content.querySelectorAll('tr:not(* > *)');    // top-level <tr>s

shadowRoot.querySelectorAll(':host > *');              // top-level elements of a shadow root

Why :scope matches nothing

When you call element.querySelectorAll(), :scope matches element. That's what makes :scope > li mean "my own <li> children". When you call it on a node that isn't an element, there's no element for :scope to match:

Chromium and Firefox don't treat the fragment as a stand-in for :scope, so :scope matches no node at all. Any compound like :scope > tr then has nothing to be a child of, and the result is empty. No error is thrown, which makes it easy to miss.

This mostly bites code that clones templates. template.content is where you'd naturally look for top-level nodes, and it's often where your selector came from in the first place: it worked on an element, so you moved it to the template. (If document.querySelectorAll() can't see your template's elements at all, that's a different problem, covered in Why document.querySelectorAll() Can't Find Elements Inside a <template>.)

The spec says it should work

The Selectors Level 4 draft describes exactly the code above. It calls the fragment a virtual scoping root that acts "as the parent of any root elements in the document fragment", and gives this example:

For example, if you have a DocumentFragment df, then df.querySelectorAll(":scope > .foo") matches all the .foo elements that are "top-level" in the document fragment (those that have the document fragment as their parentNode).

Browsers don't do this. The shared web-platform-tests file for :scope asserts the opposite: :scope > div on a shadow root or a fragment "should not match". The spec text and the tests have disagreed for years, and the CSS Working Group issues about it (#3016, #7261) are still open. Tools that follow the spec text behave differently from browsers; see this markuplint issue. Until that's settled, don't use :scope on anything that isn't an element.

What I tested

I ran these in Chromium 159 and Firefox 159. Each root contains <div class="top"><div class="inner"></div></div><p class="top"></p>. Both browsers gave the same results:

Root                         Selector         Result
template.content             :scope > *       (none)
template.content.cloneNode() :scope > *       (none)
createDocumentFragment()     :scope > *       (none)
shadowRoot                   :scope > *       (none)
template.content             :scope div       (none)
template.content             :scope           (none)
template.content             :not(* > *)     div.top, p.top
template.content             div:not(* > *)  div.top
shadowRoot                   :not(* > *)     div.top, p.top
shadowRoot                   :host > *        div.top, p.top
document                     :scope           html
document                     :scope > *       head, body

I couldn't test Safari, so use the demo below to check it.

Fix 1: :not(* > *)

The top-level elements of a fragment are exactly the elements whose parent isn't an element. * > * matches every element that has a parent element, so :not(* > *) matches the rest:

const content = template.content;

content.querySelectorAll(':not(* > *)');         // all top-level elements
content.querySelectorAll('tr:not(* > *)');       // top-level <tr>s only
content.querySelectorAll(':not(* > *) > td');    // <td>s of the top-level elements

This works on any fragment, including a shadow root, and you can build on it the way you would with :scope: put :not(* > *) wherever you'd have written :scope > *.

Don't use it on an element. Inside an element every match has a parent element, so element.querySelectorAll(':not(* > *)') always returns an empty list. If a function might receive either kind of root, use :scope for elements and :not(* > *) for everything else:

function queryChildren(root, selector) {
  const top = root instanceof Element ? ':scope > ' : ':not(* > *)';

  return root.querySelectorAll(`${top}:is(${selector})`);
}

queryChildren(template.content, 'tr');  // top-level <tr>s
queryChildren(table.tBodies[0], 'tr');  // the tbody's own <tr>s

:not() with a complex selector like * > * is part of Selectors Level 4, which Chrome has supported since version 88, Firefox since 84 and Safari since 9.

Fix 2: :host > * in a shadow root

Inside a shadow tree, :host matches the shadow host, and the host acts as the parent of the shadow root's top-level elements. So in a shadow root, :host > * does what :scope > * doesn't:

const root = host.attachShadow({ mode: 'open' });
root.innerHTML = '<div><div></div></div><p></p>';

root.querySelectorAll(':scope > *');  // NodeList []
root.querySelectorAll(':host > *');   // NodeList(2) [div, p]
root.querySelectorAll(':host');       // NodeList []  (the host isn't inside the root)

This only works in shadow roots. In a template or a plain fragment there's no host, so use :not(* > *) there.

Fix 3: filter .children

Every DocumentFragment has a children collection holding its top-level elements. If you only need one level, filter it with matches():

const rows = [...template.content.children].filter((el) => el.matches('tr'));

This doesn't depend on any selector support, and it's easy to read. It doesn't combine with the rest of a selector, though: for "the <td>s of the top-level rows" you'd need a second query on each row.

Gotcha: :scope div is empty too

It's not only the child combinator. Since :scope matches no node, nothing can be its descendant either, so :scope div and :scope .item also return nothing on a fragment, even though div and .item on their own would match.

On an element, people often add :scope to every selector out of habit. If you share selectors between element roots and fragment roots, that habit turns working queries into empty ones. Leave :scope out unless you need it to mean "a direct child of the root".

Gotcha: on a document, :scope is <html>

Document isn't an element either, but it behaves differently. There, :scope matches the document element, so document.querySelectorAll(':scope > *') returns <head> and <body>, not <html>. The same is true for a document from DOMParser.

So of the three node types that have querySelectorAll(), only elements and documents give :scope something to match. For a fragment, nothing matches.

Try it in your browser

The button runs each selector on a template's content and on a shadow root in your browser. The template contains <div class="top"><div class="inner"></div></div><p class="top"></p>.

Results will appear here.

Summary