DOM Nodes
In the DOM, everything is a Node — elements, text, comments, the document itself. nodeType tells you which.
The main Node types
| nodeType | Constant | What it is |
|---|---|---|
| 1 | ELEMENT_NODE | An HTML/SVG element (<div>, <p>, …). |
| 3 | TEXT_NODE | Text — the words between tags. |
| 8 | COMMENT_NODE | <!-- … -->. |
| 9 | DOCUMENT_NODE | The document itself. |
| 11 | DOCUMENT_FRAGMENT_NODE | An off-DOM container for batch inserts. |
Creating, inserting, removing
JS
// Create
const li = document.createElement("li");
const txt = document.createTextNode("hello");
const frag = document.createDocumentFragment();
// Insert
parent.append(li); // append children (nodes or strings)
parent.prepend(li); // prepend
ref.before(li); // before this sibling
ref.after(li); // after this sibling
ref.replaceWith(li); // swap out
// Remove
li.remove();
DocumentFragment — batch inserts
JS
const frag = document.createDocumentFragment();
for (const name of names) {
const li = document.createElement("li");
li.textContent = name;
frag.append(li);
}
list.append(frag); // ONE layout pass instead of N
nodeName vs. tagName
nodeNameworks on every node — for elements it returns uppercase tag ("DIV"), for text nodes it returns"#text".tagNameonly exists on Elements.
Tip: Use
DocumentFragment any time you'd write a loop that appends many items. It's an off-screen mini-DOM you flush at the end.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from DOM Nodes!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Batch-insert many items efficiently using an off-screen container.
const frag = document.
();
A long camelCase method.
Discussion
Loading…