Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Inspecting and modifying DOM nodes with `Node`

Test whether a node belongs to a subtree, read its parent or first child, insert a node at a specific position, and merge adjacent text nodes.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

node.contains(otherNode)
node.normalize()
node.parentNode
node.firstChild
parent.insertBefore(newNode, referenceNode)
parent.insertBefore(newNode, null)

Node.contains/normalize/parentNode/firstChild/insertBefore groups five members of the web DOM’s Node interface, not ECMAScript 2024 features. Use them on node objects. In a browser, the example uses the native DOM; in Node.js, it uses a minimal model of the element and text nodes shown.

node.contains(otherNode) returns true if otherNode is the same node or a descendant at any depth. It returns false for null. The test follows the same node tree: it works in a detached subtree and does not cross from a host into its shadow tree.

parentNode and firstChild are read-only properties. The first gives the immediate parent or null; the parent can be a Document or DocumentFragment, which parentElement would not return. The second gives the first direct child or null. That child can be a comment or a whitespace text node; use firstElementChild when you want the first child element.

parent.insertBefore(newNode, referenceNode) inserts before the specified direct child. Pass the second argument explicitly: null inserts at the end. Using parent.firstChild therefore prepends even when the parent is empty. The method moves an existing node rather than copying it and returns newNode; for a DocumentFragment, it moves the fragment’s children and returns the emptied fragment. A reference node that is not a direct child raises NotFoundError; an invalid hierarchy, such as a cycle, raises HierarchyRequestError.

node.normalize() changes the subtree in place: it removes empty ordinary text nodes and merges adjacent ones in text order. It does not strip whitespace and returns undefined. A saved reference to a removed node still points to that object, but the object no longer has a parent. This is not the Unicode normalization performed by String.prototype.normalize().

Examples

{
  // Node.js has no document. This fallback models only the element and
  // text-node behavior used below; in a browser, use the native DOM.
  class ExampleNode {
    parentNode = null;
    childNodes = [];

    constructor(data = null) {
      this.data = data;
    }

    get firstChild() {
      return this.childNodes[0] ?? null;
    }

    contains(node) {
      for (let current = node; current !== null; current = current.parentNode) {
        if (current === this) return true;
      }
      return false;
    }

    #detach() {
      const parent = this.parentNode;
      if (parent !== null) {
        parent.childNodes.splice(parent.childNodes.indexOf(this), 1);
        this.parentNode = null;
      }
    }

    insertBefore(node, reference) {
      if (node === reference) return node;
      node.#detach();
      const index = reference === null
        ? this.childNodes.length
        : this.childNodes.indexOf(reference);
      this.childNodes.splice(index, 0, node);
      node.parentNode = this;
      return node;
    }

    normalize() {
      let previousText = null;
      for (const child of [...this.childNodes]) {
        if (child.data === null) {
          child.normalize();
          previousText = null;
        } else if (child.data === "") {
          child.#detach();
        } else if (previousText !== null) {
          previousText.data += child.data;
          child.#detach();
        } else {
          previousText = child;
        }
      }
    }
  }

  const doc = globalThis.document ?? {
    createElement: () => new ExampleNode(),
    createTextNode: (data) => new ExampleNode(data)
  };
  const root = doc.createElement("div");
  const a = doc.createTextNode("A");
  const b = doc.createTextNode("B");
  const empty = doc.createTextNode("");

  root.insertBefore(a, root.firstChild);
  root.insertBefore(b, null);
  root.insertBefore(empty, root.firstChild);
  console.log(JSON.stringify([
    root.contains(root), root.contains(null), root.contains(b),
    b.parentNode === root, root.firstChild === empty, root.childNodes.length
  ]));

  root.normalize();
  console.log(JSON.stringify([
    root.firstChild === a, root.firstChild.data, root.contains(b),
    b.parentNode === null, root.childNodes.length
  ]));
}

Result

[true,false,true,true,true,3]
[true,"AB",false,true,1]

Run this in a browser console or with Node.js. `root` stays outside the document. After normalization, `a` holds `AB` and is the only child, while `b` is detached.

Related lessons

  • JavaScript · Lesson 33 · Intermediate · Version: 3

Sources