function traverseTree(root, visitor) {
// Visit the root first
visitor(root);
for (const child of root.childNodes) {
// Recursively visit each child in order
// Each child subtree is completely visited before moving to the next
traverseTree(child, visitor);
}
}Selection and traversal on the DOM tree / notebook
Selection and traversal on the DOM tree
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
function selectTree(root, visitor) {
// visitor successfully matches the root node; return without going further
if (visitor(root)) return root;
for (const child of root.childNodes) {
const result = selectTree(child, visitor);
// A result is successfully found within the subtree at child
if (result !== null) return result;
}
// No match found anywhere in the subtree at root
return null;
}
function selectTreeMulti(root, visitor, collection) {
if (visitor(root)) collection.push(root);
for (const child of root.childNodes) {
selectTreeMulti(child, visitor, collection);
}
return collection;
}<div id="container"></div>
<div class="profile big"></div>const containerDiv = document.getElementById("container");
// containerDiv is an HTMLDivElement
const profileDivs = document.getElementsByClassName("profile");
// profileDivs is an HTMLCollection containing an HTMLDivElement
const profileDivs2 = document.getElementsByTagName("div");
// profileDivs2 is an HTMLCollection containing both HTMLDivElements/* document.getElementById("container") */
#container {
}
/* document.getElementsByClassName("profile") */
.profile {
}
/* document.getElementsByClassName("profile big") */
.profile.big {
}
/* document.getElementsByTagName("div") */
div {
}
/* document.getElementsByTagName("*") */
* {
}const special = document.querySelectorAll("p.warning, p.note");const el = document.querySelector("#main, #basic, #exclamation");document.getElementById("container");
// Is equivalent to:
document.querySelector("#container");
document.getElementsByClassName("profile big");
// Is equivalent to:
document.querySelectorAll(".profile.big");
document.getElementsByTagName("div");
// Is equivalent to:
document.querySelectorAll("div"); const id = "item:42";
const item = document.querySelector(`#${CSS.escape(id)}`);
// document.getElementById(id) needs no escaping.<div>
<section id="main">
<p class="note">A direct child.</p>
<div>
<p class="note">A nested paragraph.</p>
</div>
</section>
</div>const main = document.getElementById("main");
const allNotes = main.querySelectorAll("div p"); // Both paragraphs
const childNote = main.querySelectorAll(":scope div p"); // Only the second
const childNote2 = main.querySelectorAll(":scope > p"); // Only the firstconst innerNote = document.querySelector("#main div p.note");
console.log(innerNote.closest("section").id); // "main"const paragraphs = document.querySelectorAll("p");
console.log(paragraphs.length);
console.log(paragraphs[0]);
for (const para of paragraphs) {
// ...
}const paragraphs = [...document.querySelectorAll("p")];
const paragraphs2 = Array.from(document.querySelectorAll("p"));
const texts = paragraphs.map((p) => p.textContent);const sections = document.getElementsByTagName("section");
const main = sections.namedItem("main");
const main2 = sections["main"];const container = document.createElement("div");
const paragraph = document.createElement("p");
paragraph.className = "note";
container.append(paragraph);
const liveList = container.getElementsByClassName("note");
console.log(liveList.length); // 1
paragraph.classList.remove("note");
console.log(liveList.length); // 0const container = document.createElement("div");
const paragraph = document.createElement("p");
paragraph.className = "note";
container.append(paragraph);
const staticList = container.querySelectorAll(".note");
console.log(staticList.length); // 1
paragraph.classList.remove("note");
console.log(staticList.length); // 1
console.log(staticList[0].className); // ""const notes = document.getElementsByClassName("note");
for (const note of notes) {
// This simultaneously removes this element from the collection, shifting
// all later elements, so the next iteration doesn't visit the next element
note.classList.remove("note");
}for (const descendant of element.querySelectorAll("*")) {
// Visit every single descendant element in this subtree
}const nodeIterator = document.createNodeIterator(document);
let node = nodeIterator.nextNode();
while (node) {
console.log(node.nodeName);
node = nodeIterator.nextNode();
}const iterator = document.createNodeIterator(
document.body,
NodeFilter.SHOW_TEXT,
(node) =>
node.data.trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP,
);let node;
while ((node = iterator.nextNode())) {
console.log(node.data);
}<article id="article">
<p>Read <strong>this</strong> paragraph.</p>
<aside data-skip><p>Ignore this note.</p></aside>
<p>Read this paragraph too.</p>
</article>const article = document.getElementById("article");
const walker = document.createTreeWalker(
article,
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT,
(node) => {
if (node.nodeType === Node.ELEMENT_NODE) {
return node.hasAttribute("data-skip")
? NodeFilter.FILTER_REJECT
: NodeFilter.FILTER_SKIP;
}
return node.data.trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
},
);
const parts = [];
let node;
while ((node = walker.nextNode())) {
parts.push(node.data);
}
console.log(parts.join(""));
// "Read this paragraph.Read this paragraph too."