iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

DOM Nodes

In the DOM, everything is a Node — elements, text, comments, the document itself. nodeType tells you which.

The main Node types

nodeTypeConstantWhat it is
1ELEMENT_NODEAn HTML/SVG element (<div>, <p>, …).
3TEXT_NODEText — the words between tags.
8COMMENT_NODE<!-- … -->.
9DOCUMENT_NODEThe document itself.
11DOCUMENT_FRAGMENT_NODEAn 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

  • nodeName works on every node — for elements it returns uppercase tag ("DIV"), for text nodes it returns "#text".
  • tagName only 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. ();

Test yourself

Q1. `nodeType === 1` means…
Q2. Batch-insert many nodes efficiently with…
Q3. Modern remove-this-node call is…

Discussion

Loading…