Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

DOM nodes: type, value, and child nodes

Tell text nodes from elements, read the value of an individual node, and traverse direct children without overlooking changes to the live list.

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

Syntax

node.nodeType
node.nodeValue
node.nodeValue = text
node.childNodes
node.nodeType === Node.TEXT_NODE
node.nodeType === Node.ELEMENT_NODE

The read-only node.nodeType property returns an integer that identifies the kind of node. Compare it with === against constants on the Node interface: Node.TEXT_NODE (3) identifies a text node, and Node.ELEMENT_NODE (1) identifies an element. An element and the text inside it are separate nodes. These are web-platform DOM APIs, not part of ECMAScript 2024; a JavaScript runtime need not provide the DOM.

node.nodeValue refers to the node itself. On a text node, it reads the text, and assigning a string replaces that text without parsing it as HTML. A comment also has a string value. On an element, the property returns null, and assigning to it has no effect, even if the element contains text. To read an element's combined descendant text, excluding comments and processing instructions, use element.textContent.

The read-only node.childNodes property gives you a live NodeList of direct children, not all descendants. It is indexed from zero and is not an array. It includes elements, text, and comments. Indentation and line breaks in HTML can become whitespace-only text nodes, so childNodes[0] need not be an element. For direct element children only, use element.children.

A saved reference to the list still reflects children being added or removed. Removing a node during a forward pass can shift indices and make you skip the next node. If you need a fixed set of entries to iterate over, use Array.from(node.childNodes) before editing. The array holds references to the same nodes, not clones.

Examples

{
  const { document, Node } = globalThis.document && globalThis.Node
    ? globalThis
    : createExampleDOM();

  const parent = document.createElement("div");
  const children = parent.childNodes;
  console.log(children.length);

  const text = document.createTextNode(" ");
  const span = document.createElement("span");
  span.appendChild(document.createTextNode("inside"));
  parent.appendChild(text);
  parent.appendChild(span);
  console.log(children.length);

  for (const child of children) {
    const type = child.nodeType;
    const kind = type === Node.TEXT_NODE ? "text" :
      type === Node.ELEMENT_NODE ? "element" : "other";
    console.log(JSON.stringify([kind, type, child.nodeValue]));
  }

  span.nodeValue = "ignored";
  console.log(span.textContent);
  text.nodeValue = "outside";
  console.log(text.nodeValue);

  // Plain Node.js has no DOM. This local model implements only the
  // element, text, and live-list operations used by this example.
  function createExampleDOM() {
    class ExampleNode {
      static TEXT_NODE = 3;
      static ELEMENT_NODE = 1;

      #type;
      #value;
      #children = [];
      #list;

      constructor(type, value = null) {
        this.#type = type;
        this.#value = value;
        const children = this.#children;
        this.#list = {
          get length() { return children.length; },
          [Symbol.iterator]() { return children[Symbol.iterator](); }
        };
      }

      get nodeType() { return this.#type; }
      get childNodes() { return this.#list; }
      get nodeValue() { return this.#value; }
      set nodeValue(value) {
        if (this.#type === ExampleNode.TEXT_NODE) {
          this.#value = value === null ? "" : String(value);
        }
      }

      get textContent() {
        if (this.#type === ExampleNode.TEXT_NODE) return this.#value;
        return this.#children.map(child => child.textContent).join("");
      }

      appendChild(child) {
        this.#children.push(child);
        return child;
      }
    }

    return {
      Node: ExampleNode,
      document: {
        createElement: () => new ExampleNode(ExampleNode.ELEMENT_NODE),
        createTextNode: value => new ExampleNode(ExampleNode.TEXT_NODE, String(value))
      }
    };
  }
}

Result

0
2
["text",3," "]
["element",1,null]
inside
outside

Run the code in a browser console on an HTML page. The saved list grows from `0` to `2` even though the parent is not attached to the page. The JSON line for the text node shows one space inside quotation marks.

Related lessons

  • JavaScript · Lesson 16 · Advanced · Version: 4

Sources