Why document.querySelectorAll() Can't Find Elements Inside a <template>

You put some markup inside a <template>, you can see it in the page source, and yet document.querySelectorAll() acts as if it doesn't exist:

<ul id="users"></ul>

<template id="user-row">
  <li><span class="name"></span></li>
</template>
document.querySelectorAll('.name').length; // 0

Short answer: the contents of a <template> are not part of the document. They live in a separate DocumentFragment, available as template.content, so that's where you have to query:

const template = document.querySelector('#user-row');

template.content.querySelectorAll('.name').length; // 1

Why the document can't see template contents

When the HTML parser reaches a <template>, it doesn't attach the markup inside it as children of the template element. Instead it builds those nodes in a separate DocumentFragment that belongs to a different, inert document, and exposes that fragment as the template's content property.

document.querySelectorAll() searches the document's tree. The template element is in that tree, but as far as the tree is concerned, the template is empty:

template.children.length;          // 0
template.childNodes.length;        // 0
template.querySelectorAll('li');   // empty NodeList

template.content.children.length;  // 1 (the <li>)

Two things make this confusing. Your browser's developer tools show the markup nested under the template, which makes it look like ordinary children. Look closer and you'll see it sits under a #document-fragment node. And template.innerHTML returns the markup too, because for templates it reads from content. The markup is there; it just isn't in the document.

This is deliberate. Template contents are meant to be inert until you use them: images inside them don't load, scripts don't run, styles don't apply, and nothing inside them shows up when you query or traverse the page. That's what lets you keep markup in the page without it affecting anything.

For the same reason, a selector can't reach "through" a template. This also returns nothing:

document.querySelectorAll('#user-row li'); // empty NodeList

The fix: query template.content

DocumentFragment has the same query methods as an element, so everything you know still works. You just call it on the fragment:

const template = document.querySelector('#user-row');

template.content.querySelector('li');
template.content.querySelectorAll('.name');
template.content.getElementById('some-id');

Query the clone, not the template

Most of the time you don't want the template's own nodes. You want a copy you can fill in and insert into the page. So clone first, then query the clone:

const template = document.querySelector('#user-row');
const list = document.querySelector('#users');

for (const name of ['Ada', 'Grace', 'Margaret']) {
  const row = template.content.cloneNode(true);

  row.querySelector('.name').textContent = name;

  list.append(row);
}

Querying template.content directly and changing what you find changes the template itself, so every clone made afterwards inherits the change. That's useful for setting defaults once, and a confusing bug when you didn't mean to:

template.content.querySelector('.name').textContent = 'Unknown';

// Every row cloned from now on starts with "Unknown".

Gotcha: the clone is empty after you insert it

A DocumentFragment is a temporary container. When you append it to the page, its children are moved out of it, which leaves the fragment empty:

const row = template.content.cloneNode(true);
list.append(row);

row.querySelectorAll('.name').length; // 0

If you need a reference to an element after inserting it, grab it from the fragment before you append:

const row = template.content.cloneNode(true);
const item = row.querySelector('li');

list.append(row);

item.isConnected; // true, and you still have it

Gotcha: custom elements inside a template aren't upgraded

Because template contents belong to an inert document, custom elements inside them are never upgraded there. If you query one, you get a plain element without your class's methods:

<template id="card">
  <user-card></user-card>
</template>
class UserCard extends HTMLElement {}
customElements.define('user-card', UserCard);

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

template.content.querySelector('user-card') instanceof UserCard; // false

cloneNode() keeps the copy in that same inert document, so the clone's custom elements are only upgraded once you insert them into the page. If you need them upgraded while you're still filling in the copy, use document.importNode() instead, which creates the copy in the main document:

template.content.cloneNode(true)
  .querySelector('user-card') instanceof UserCard; // false

document.importNode(template.content, true)
  .querySelector('user-card') instanceof UserCard; // true

Gotcha: nested templates need their own .content

A template inside another template is part of the outer template's content, so document.querySelectorAll('template') won't find it. You have to go through each level:

const outer = document.querySelector('#outer');
const inner = outer.content.querySelector('template');

inner.content.querySelectorAll('li');

Gotcha: shadowrootmode templates disappear

A template with a shadowrootmode attribute (declarative shadow DOM) is different again. The parser doesn't keep it as a template at all: it turns its contents into a shadow root on the parent element and removes the template. There's no template.content to query. Query the shadow root instead:

<user-card>
  <template shadowrootmode="open">
    <span class="name"></span>
  </template>
</user-card>
document.querySelector('user-card template');  // null

document.querySelector('user-card')
  .shadowRoot.querySelectorAll('.name');       // 1 match

Gotcha: framework templates (Alpine.js and friends)

Some libraries use <template> for you. In Alpine.js, for example, x-for and x-if must be placed on a template element. Alpine clones the template's contents and inserts the rendered elements after the template, as its siblings.

So with a framework, the elements you want usually aren't in template.content at all. They're the rendered copies in the document. Query the document as normal, but only after the framework has rendered them (in Alpine, inside $nextTick or after the alpine:initialized event).

Try it in your browser

This page contains a real template. Press the button to run the queries from this article against it and see what your browser returns:

<template id="demo-template">
  <li><span class="demo-name">Ada</span></li>
  <demo-card></demo-card>
</template>
Results will appear here.

Summary