Skip to content

Nodes & Navigation

According to the W3C HTML DOM standard, everything in an HTML document is a node: - The entire document is a document node. - Every HTML element is an element node. - The text inside HTML elements are text nodes. - All comments are comment nodes.

You can use the following node properties to navigate between nodes with JavaScript:

  • parentNode
  • childNodes[n]
  • firstChild / lastChild
  • nextSibling / previousSibling
const myTitle = document.getElementById("demo").parentNode.nodeName;

Creating New Elements

To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.

// 1. Create element
const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);

// 2. Find parent
const element = document.getElementById("div1");

// 3. Append
element.appendChild(para);

Removing Elements

const elmnt = document.getElementById("p1");
elmnt.remove();

Modern Methods

Modern JS has cleaner methods for manipulation: append(), prepend(), before(), after().