CKTIS / JavaScript
Select a descendant with querySelector() and update its contents with innerHTML
Find the first descendant that matches a CSS selector, handle a missing match, and read or replace the markup inside the selected element.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
const target = root.querySelector(selectors);
if (target !== null) {
const previousMarkup = target.innerHTML;
target.innerHTML = markup;
}Element.querySelector/innerHTML pairs two operations: finding an element and working with its contents. root.querySelector(selectors) accepts a string containing a CSS selector or a comma-separated selector list. It returns the first matching descendant in DOM tree order, regardless of the order of selectors in the list. It never returns root itself. No match returns null; invalid selector syntax throws a DOMException named SyntaxError. Check the result before reading or assigning a property.
The returned element must be below root, but selector matching can consider ancestors outside that subtree. Use :scope > .message to match only direct children of root with the message class. This is not a document-wide search like document.querySelector().
Reading target.innerHTML returns a string that serializes the contents, omitting the element's own tags and any shadow roots. Assigning it parses a fragment in the element's context and replaces its children, not the element itself. For a template element, it replaces the template contents instead. Saved references and listeners still belong to the old, detached nodes, not the replacements. In an XML document, malformed markup throws SyntaxError on assignment; reading can throw InvalidStateError if XML serialization fails. Both are DOMExceptions.
Do not assign untrusted input directly to innerHTML: it does not sanitize markup by default and can lead to XSS. Use textContent for plain text. If you need markup from an untrusted source, sanitize it first. Trusted Types do not sanitize on their own. Where supported and enforced by CSP, assigning a plain string without a suitable default policy throws TypeError; pass TrustedHTML from a sanitizing policy instead.
These are web platform APIs, not part of ECMAScript 2024. Check whether the runtime provides a DOM and supports the security features you need.
Examples
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>querySelector() and innerHTML</title>
</head>
<body>
<script>
{
const panel = document.createElement("div");
panel.innerHTML = '<p class="message"><em>Before</em></p><p class="message">Unchanged</p>';
const target = panel.querySelector(".message");
if (target !== null) {
const oldChild = target.firstElementChild;
console.log(target.innerHTML);
target.innerHTML = "<strong>After</strong>";
console.log(target.innerHTML);
console.log(oldChild.parentNode === null);
console.log(target.nextElementSibling.textContent);
}
console.log(panel.querySelector(".missing") === null);
}
</script>
</body>
</html>Result
<em>Before</em> <strong>After</strong> true Unchanged true
Save the example as an `.html` file and open it in a browser without a CSP that enforces Trusted Types. Check the output in the browser console. Only the first match changes. Its old child no longer has a parent, the second element keeps the text `Unchanged`, and the query with no match returns `null`.
Related lessons
- JavaScript · Lesson 18 · Advanced · Version: 4