Why querySelectorAll() Can't Find Elements Inside <noscript>
Your page has a <noscript> fallback, often an image for
lazy loading or a tracking pixel:
<noscript id="fallback">
<img src="/photos/beach.jpg" alt="Beach at sunset">
</noscript>
You can see the <img> in the page source, but your script can't
find it:
document.querySelectorAll('noscript img').length; // 0
document.querySelector('#fallback').children.length; // 0
Short answer: when JavaScript is enabled, the browser doesn't parse
the contents of <noscript> as HTML. It keeps them as a single
piece of text. Parse that text yourself, then query the result:
const noscript = document.querySelector('#fallback');
const template = document.createElement('template');
template.innerHTML = noscript.textContent;
template.content.querySelectorAll('img'); // NodeList [img]
Why there are no elements inside <noscript>
The HTML parser handles <noscript> differently depending on
whether scripting is enabled. When it's disabled, the contents are parsed as normal
HTML and shown on the page. When it's enabled, the parser reads everything up to
</noscript> as raw text, the same way it treats the contents of a
<script> or <style> element.
Your querySelectorAll() call is JavaScript, so scripting is always
enabled when it runs. That means it always sees the text version. The
<noscript> element itself is a normal element and can be selected,
but it has exactly one child, a text node:
const noscript = document.querySelector('#fallback');
noscript.children.length; // 0
noscript.childNodes.length; // 1
noscript.firstChild.nodeType; // 3 (Node.TEXT_NODE)
noscript.textContent; // '\n <img src="/photos/beach.jpg" alt="Beach at sunset">\n'
The same happens to <noscript> in the <head>,
for example a fallback <link rel="stylesheet">: the element is
there, but the <link> inside isn't.
One useful detail: because the text is never parsed, textContent holds
the original markup exactly as written, character entities included. If the source
says alt="Tom & Jerry", textContent contains
&, not &. That's what you want, since it's
valid HTML you can pass straight to a parser.
The fix: parse the text with a <template>
Set the text as the innerHTML of a <template>, then
query its content:
function parseNoscript(noscript) {
const template = document.createElement('template');
template.innerHTML = noscript.textContent;
return template.content;
}
const content = parseNoscript(document.querySelector('#fallback'));
content.querySelectorAll('img'); // NodeList [img]
content.querySelector('img').alt; // "Beach at sunset"
To query every <noscript> on the page at once:
const images = [...document.querySelectorAll('noscript')]
.flatMap((noscript) => [...parseNoscript(noscript).querySelectorAll('img')]);
A <template> is a good choice here because its content is inert:
images in it don't load and scripts don't run. You get elements you can inspect
without side effects. (For more about querying template content, see
why
document.querySelectorAll() can't find elements inside a
<template>.)
Alternative: DOMParser
DOMParser also works. It creates a separate, inert document, so nothing
in it loads either:
const doc = new DOMParser().parseFromString(noscript.textContent, 'text/html');
doc.querySelectorAll('img'); // NodeList [img]
The difference is that you get a whole document instead of a fragment. A
<link> or <style> from a
<noscript> in the head ends up in doc.head and the
rest in doc.body, so query doc rather than
doc.body.
Using the fallback content on the page
Sometimes you want the fallback to appear even though JavaScript is on, for example
when your lazy-loading script fails or you've decided not to run it. Replace the
<noscript> with the parsed content:
for (const noscript of document.querySelectorAll('noscript.lazy-fallback')) {
noscript.replaceWith(parseNoscript(noscript));
}
Once the elements are in the document, they're ordinary elements: images start
loading, and document.querySelectorAll() can find them.
Gotcha: some ways of parsing start loading images
You might reach for a <div> instead of a template:
const div = document.createElement('div');
div.innerHTML = noscript.textContent; // the browser starts downloading the images
div.querySelectorAll('img');
This finds the elements, but because the <div> belongs to the live
document, the browser starts fetching every image as soon as it's parsed, even though
the <div> is never added to the page. That defeats the point of a
lazy-loading fallback, and with a tracking pixel it fires the request. Use a
<template> or DOMParser, which don't load anything.
Gotcha: other parsing APIs don't agree
Whether a <noscript> becomes elements or text depends on the
parser, so the same markup can give different results. I tested this markup in
Chromium 159 and Firefox 159:
'<noscript><img></noscript>'
API Chromium 159 Firefox 159
el.innerHTML = markup (element in the page) text text
range.createContextualFragment(markup) text text
Document.parseHTMLUnsafe(markup) text text
template.innerHTML = markup elements text
new DOMParser().parseFromString(markup, ...) elements elements
DOMParser parses with scripting disabled, so its
<noscript> contents become elements. The others mostly use
scripting enabled and keep them as text, except that Chromium parses
<noscript> inside template.innerHTML as elements and
Firefox doesn't.
None of this affects the fix above, which parses the noscript's text and not the
<noscript> tag itself. But if you insert HTML containing a
<noscript> and then query inside it, test in more than one browser.
When querying <noscript> does work
If you fetch a page and parse it with DOMParser, its
<noscript> contents are elements, and
querySelectorAll('noscript img') works directly:
const html = await (await fetch('/some-page')).text();
const doc = new DOMParser().parseFromString(html, 'text/html');
doc.querySelectorAll('noscript img'); // finds the images
The same is true of a <noscript> you build with DOM methods such as
createElement() and append(), since no parser is involved.
Server-side HTML parsers vary: some follow the browser and treat the contents as text,
so check how yours handles it.
Try it in your browser
This page contains a <noscript> with an image and a paragraph
(you won't see it, because JavaScript is on). Press the button to run the queries
from this article against it:
<noscript id="demo-noscript">
<img src="/demo-does-not-exist.jpg" alt="Tom & Jerry">
<p class="message">Please enable JavaScript.</p>
</noscript>
Results will appear here.
Summary
-
With JavaScript enabled, everything inside
<noscript>is stored as one text node, soquerySelectorAll()finds no elements in it. Since your query is JavaScript, that's always the case when it runs. -
noscript.textContentholds the original markup. Parse it withtemplate.innerHTMLand querytemplate.content, or useDOMParser. -
Don't parse it with a
<div>: that starts loading the images. Templates andDOMParserdon't load anything. -
Use
noscript.replaceWith(template.content)to put the fallback on the page. -
Pages parsed with
DOMParser, for example fetched HTML, do have elements inside<noscript>, so you can query them directly.