How to Wait for an Element to Appear in the DOM
Wait for an element to appear in the DOM with a MutationObserver promise, a timeout and an AbortSignal, and avoid the polling loops that waste CPU in browsers.

Scripts that run before the page has finished building look for an element that is not there yet. Content scripts in browser extensions, widgets injected by tag managers, code that runs against a framework that renders on its own schedule and tests for single-page apps all face it: the element will exist soon, and the code needs to know when. The common bad answer is setInterval that polls querySelector every 100 milliseconds until something turns up. It wastes CPU, adds up to 100 milliseconds of delay and is hard to stop cleanly. The right tool is a MutationObserver, which tells you when the DOM changes. This post builds a waitForElement function that returns a promise, checks first for an element that already exists, rejects after a timeout and supports cancellation. It uses APIs available in every current browser, and the same ideas carry over to testing libraries. For the promise pieces, see wrapping an event with Promise.withResolvers.
Check first, then observe
The element may already exist, so look before you wait. Then start an observer on a root node, and on each batch of changes check again.
export function waitForElement(selector, { root = document, signal } = {}) {
return new Promise((resolve, reject) => {
const existing = root.querySelector(selector);
if (existing) return resolve(existing);
if (signal?.aborted) return reject(signal.reason);
const observer = new MutationObserver(() => {
const found = root.querySelector(selector);
if (found) {
observer.disconnect();
signal?.removeEventListener("abort", onAbort);
resolve(found);
}
});
function onAbort() {
observer.disconnect();
reject(signal.reason);
}
observer.observe(root === document ? document.documentElement : root, {
childList: true,
subtree: true,
});
signal?.addEventListener("abort", onAbort, { once: true });
});
}childList: true reports nodes being added or removed, and subtree: true extends that to all descendants, which is what you need when the element may appear anywhere. The observer callback runs after the DOM changes, in a microtask, so it does not slow rendering. When the element is found, the observer disconnects, so nothing keeps running after the promise settles.
Using it
Call it where you need the element, and await the result. Suppose a script waits for a comments section that the page loads later.
import { waitForElement } from "./wait-for-element.js";
setTimeout(() => {
const section = document.createElement("section");
section.id = "comments";
document.body.append(section);
}, 100);
const comments = await waitForElement("#comments");
console.log(comments.tagName, comments.id);SECTION commentsThe timer plays the part of the framework that renders the section after a delay. The script gets its element the moment it is inserted, without a polling interval and without knowing how long it will take.
Add a timeout
A promise that waits for something that never appears hangs the code behind it. Pair the wait with a deadline. AbortSignal.timeout makes this a one-liner, and waitForElement already accepts a signal.
import { waitForElement } from "./wait-for-element.js";
try {
await waitForElement("#never-rendered", { signal: AbortSignal.timeout(500) });
} catch (error) {
console.log(error.name);
}TimeoutErrorAfter half a second the signal aborts, the observer disconnects and the promise rejects with a TimeoutError. The caller can then show a message, log the failure or fall back. To stop on either a timeout or a user action, combine the signals, as in combining AbortSignals from multiple sources.
Observe a smaller root
Watching the whole document means the callback runs for every change anywhere on the page, such as ads loading and animations inserting nodes. If you know a container that will hold the element, pass it as the root, and the observer runs only for changes inside it.
import { waitForElement } from "./wait-for-element.js";
const panel = document.createElement("div");
document.body.append(panel);
setTimeout(() => {
const row = document.createElement("li");
row.className = "result";
panel.append(row);
}, 50);
const row = await waitForElement(".result", { root: panel });
console.log(row.className);resultA narrow root makes the callback cheap. If the container itself may not exist yet, wait for it first with the document as the root, then wait for the inner element with the container as the root.
Wait for an attribute or a state, not only presence
An element can exist and still not be ready: a button that is disabled until a check completes, a panel that gains a loaded class. The observer can watch attributes too. Generalize the function to take a predicate, so it waits until the element exists and passes your test.
export function waitForCondition(check, { root = document.documentElement, signal } = {}) {
return new Promise((resolve, reject) => {
const initial = check();
if (initial) return resolve(initial);
if (signal?.aborted) return reject(signal.reason);
const observer = new MutationObserver(() => {
const result = check();
if (result) {
observer.disconnect();
resolve(result);
}
});
observer.observe(root, { childList: true, subtree: true, attributes: true });
signal?.addEventListener(
"abort",
() => {
observer.disconnect();
reject(signal.reason);
},
{ once: true }
);
});
}
const button = document.createElement("button");
button.disabled = true;
document.body.append(button);
setTimeout(() => (button.disabled = false), 30);
const ready = await waitForCondition(() => {
const b = document.querySelector("button");
return b && !b.disabled ? b : null;
});
console.log(ready.disabled);falseAdding attributes: true makes the callback run on attribute changes, such as removing disabled. Use attributeFilter: ["disabled"] to limit it to the attributes you care about, which cuts needless callbacks on a busy page.
Why not polling
A polling loop has no connection to what the page does, so it either checks too often, wasting time on every tick, or too rarely, delaying the result. It also needs its own cleanup, which is easy to forget, so intervals keep running after the answer is known. An observer does work only when the DOM changes and tells you at the first change that makes the condition true. The one place polling is still reasonable is a condition that changes without any DOM mutation, such as a value read from a canvas or a property that scripts change directly, since the observer would never fire.
Pitfalls
Shadow DOM hides inner elements from a document-level observer and from querySelector, so observe the shadow root itself when you need something inside a component. Elements inside iframes belong to another document, which needs its own observer. And in a framework that re-renders, the element you found may be replaced by a new one with the same selector a moment later, so hold onto the reference only as long as you must, or look it up again when you need it.
Why the first check matters
Skipping the initial querySelector is the most common bug in these helpers. A MutationObserver reports only changes that happen after observe is called, so an element that is already in the page produces no mutation, and the promise would wait forever. Run the check synchronously before observing, and run it once more right after observe starts if there is any asynchronous gap between the first check and the start of observation. In the version above there is no gap, because both steps run in one task, and no DOM change can slip in between.
A related issue is timing around page load. A script that runs while the document is still parsing may find document.documentElement but no body yet. Observing document.documentElement with subtree: true covers that, since the body is one of the nodes that will be added under it. If the script runs even earlier, in a content script injected at the start of navigation, document.documentElement itself can be missing, and you need to observe the document node instead.
Using it in tests
Test code meets the same problem: after a click, an element appears when the framework finishes rendering, and the test needs it. Testing libraries provide the same helper under names such as findBy queries in Testing Library and waitFor in several runners, and they use the same observer and timeout design. If you write your own, follow the same rules they do: a default timeout of a second or so, a clear error message that includes the selector, and cleanup of the observer on both success and failure. A message such as timed out after 1000 ms waiting for "#comments" saves minutes of debugging compared with a generic timeout error.
export function timeoutError(selector, ms) {
return new Error(`timed out after ${ms} ms waiting for "${selector}"`);
}
console.log(timeoutError("#comments", 1000).message);timed out after 1000 ms waiting for "#comments"Wrap the rejection from AbortSignal.timeout in such a message when the caller benefits from knowing which selector was missing.
When the element is removed again
Some elements appear and disappear: a toast message, a loading spinner, a modal. Waiting for the element to appear is half of the story, and waiting for it to go away is the other half, and the same observer handles both. Write a second helper that resolves when querySelector returns null, using the same childList and subtree options. Combining the two lets a script wait for the spinner to appear, then wait for it to vanish, which is a reliable signal that the loading is done and the content is ready to use.


