JavaScript DOM Nodes

The Document Object Model (DOM) represents a web page as a hierarchical tree of nodes, allowing JavaScript to interact with and manipulate the structure, style, and content of documents.

Each element, attribute, and piece of text in the document is a node in the DOM.

Types of DOM Nodes

In the DOM, every part of an HTML document is a node. The main types of DOM nodes are:

  • Element Nodes:Represent HTML elements.
  • Text Nodes:Represent the text content inside elements.
  • getElementsByTagName():Selects all elements with a given tag name.
  • Comment Nodes:Represent comments in the HTML.
  • Attribute Nodes:Represent attributes of HTML elements (usually accessed through elements, not directly).

Example

// Example HTML structure
// <div id="example">Hello, <span>world!</span></div>

const example = document.getElementById("example");

// Element node
console.log(example.nodeType); // Outputs: 1 (Element node)      
console.log(example.nodeName); // Outputs: DIV      

// Text node
const textNode = example.firstChild;
console.log(textNode.nodeType); // Outputs: 3 (Text node)      
console.log(textNode.nodeName); // Outputs: Hello,     

// Text node
const commentNode = example.childNodes[2];
console.log(commentNode.nodeType); // Outputs: 8 (Comment node)      
console.log(commentNode.nodeName); // Outputs: This is a comment

Example

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
    <h1 id="heading">Welcome to CodingKoleji</h1>
    <div id="example">Hello, <span>World!</span></div>
    <script>
      // Example HTML structure
      // <div id="example">Hello, <span>world!</span></div>
      
      const example = document.getElementById("example");
      
      // Element node
      console.log(example.nodeType); // Outputs: 1 (Element node)      
      console.log(example.nodeName); // Outputs: DIV      
      
      // Text node
      const textNode = example.firstChild;
      console.log(textNode.nodeType); // Outputs: 3 (Text node)      
      console.log(textNode.nodeName); // Outputs: Hello,     
      
      // Text node
      const commentNode = example.childNodes[2];
      console.log(commentNode.nodeType); // Outputs: 8 (Comment node)      
      console.log(commentNode.nodeName); // Outputs: This is a comment
    </script>
  </body>
</html>

Creating Nodes

JavaScript allows the creation of new nodes using methods like document.createElement(), document.createTextNode()and document.createComment().

These methods create element, text, and comment nodes, respectively.

// Creating a new element node
const newDiv = document.createElement("div");
newDiv.id = "newDiv";
newDiv.textContent = "This is a new div";

// Creating a new text node
const newText = document.createTextNode("This is a new text node");

// Creating a new comment node
const newComment = document.createTextNode("his is a new comment");

// Appending nodes to the document
document.body.appendChild(newDiv);
newDiv.appendChild(newText);
document.body.appendChild(newComment);

Example

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
    <h1 id="heading">Welcome to CodingKoleji</h1>
    <script>
      const newDiv = document.createElement("div");
      newDiv.id = "newDiv";
      newDiv.textContent = "This is a new div";
      
      // Creating a new text node
      const newText = document.createTextNode("This is a new text node");
      
      // Creating a new comment node
      const newComment = document.createTextNode("his is a new comment");
      
      // Appending nodes to the document
      document.body.appendChild(newDiv);
      newDiv.appendChild(newText);
      document.body.appendChild(newComment);
    </script>
  </body>
</html>

Appending and Inserting Nodes

Nodes can be added to the DOM tree using methods like appendChild(), insertBefore()and replaceChild().

These methods allow for dynamic manipulation of the document structure.

// Creating a new element node
const parent = document.getElementById("parent");
const newChild = document.createElement("p");
newChild.textContent = "This is a new paragraph";

// Appending a child node
parent.appendChild(newChild);

// Inserting a node before another node
const referenceNode = document.getElementById("reference");
parent.insertBefore(newChild, referenceNode);

//insertBefore
const oldChild = document.getElementById("oldChild");
parent.replaceChild(newChild, oldChild);

Example

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
    <div id="parent">
      <h1 id="heading">Welcome to CodingKoleji</h1>
      <p id="reference">This is the reference paragraph.</p>
      <p id="oldChild">This is the old paragraph to be replaced.</p>
    </div>
    <script>
    // Creating a new element node
    const parent = document.getElementById("parent");
    const newChild = document.createElement("p");
    newChild.textContent = "This is a new paragraph";
    
    // Appending a child node
    parent.appendChild(newChild);
    
    // Inserting a node before another node
    const referenceNode = document.getElementById("reference");
    parent.insertBefore(newChild, referenceNode);
    
    //insertBefore
    const oldChild = document.getElementById("oldChild");
    parent.replaceChild(newChild, oldChild);
    </script>
  </body>
</html>

Removing and Cloning Nodes

Nodes can be removed from the DOM using removeChild()and cloned using cloneNode().

Cloning can create deep copies of nodes, including their descendants.

// Creating a new element node
const parent = document.getElementById("parent");
const childToRemove = document.getElementById("childToRemove");

// Removing a child node
parent.removeChild(childToRemove);

// Cloning a node
const originalNode = document.getElementById("original");
const shalloClone = originalNode.cloneNode(); // Shallow clone
const deepClone = originalNode.cloneNode(true); // Deep clone

// Appending clones to the document
document.body.appendChild(shalloClone);
document.body.appendChild(deepClone);

Example

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
    <h1 id="heading">Welcome to CodingKoleji</h1>
    <div id="parent">
      <p id="childToRemove">This is a paragraph that will be removed.</p>
    </div>
    <div id="original">
      <p >This content will be cloned.</p>
    </div>
    <script>
      // Creating a new element node
      const parent = document.getElementById("parent");
      const childToRemove = document.getElementById("childToRemove");
      
      // Removing a child node
      parent.removeChild(childToRemove);
      
      // Cloning a node
      const originalNode = document.getElementById("original");
      const shalloClone = originalNode.cloneNode(); // Shallow clone
      const deepClone = originalNode.cloneNode(true); // Deep clone
      
      // Appending clones to the document
      document.body.appendChild(shalloClone);
      document.body.appendChild(deepClone);
    </script>
  </body>
</html>

Traversing Nodes

Navigating through the DOM tree can be done using properties like parentNode, childNodes, firstChild, lastChild, nextSiblingand previousSibling.

These properties allow traversal between nodes in the document.


const listItem = document.querySelector(".list-item");

// Accessing the parent node
const parent = listItem.parentNode;
console.log(parent);

// Accessing the parent node
const children = listItem.childNodes;
children.forEach((child) => console.log(child));

// Accessing the first and last child
const firstChild = listItem.firstChild;
const lastChild = listItem.lastChild;
console.log(firstChild, lastChild);

// Accessing next and previous siblings
const nextSibling = listItem.nextSibling;
const previousSibling = listItem.previousSibling;
console.log(nextSibling, lastChild);

Example

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
      <h1 id="heading">Welcome to CodingKoleji</h1>
      <ul class="list-item">
        <li>Banana</li>
        <li>Apple</li>
        <li>Orange</li>
      </ul>
    <script>
      const listItem = document.querySelector(".list-item");
      console.log(listItem);       
      
      // Accessing the parent node
      const parent = listItem.parentNode;
      console.log(parent);
      
      // Accessing the parent node
      const children = listItem.childNodes;
      children.forEach((child) => console.log(child));
      
      // Accessing the first and last child
      const firstChild = listItem.firstChild;
      const lastChild = listItem.lastChild;
      console.log(firstChild, lastChild);
      
      // Accessing next and previous siblings
      const nextSibling = listItem.nextSibling;
      const previousSibling = listItem.previousSibling;
      console.log(nextSibling, lastChild);
    </script>
  </body>
</html>

Working with Node Properties and Methods

Each node has properties and methods that provide information and capabilities for manipulating the node

Key properties include nodeType, nodeName, nodeValueand textContentwhile essential methods include appendChild(), removeChild(), cloneNode()and replaceChild().


const node = document.getElementById("exampleNode");

// Node properties
console.log(node.nodeType); // Type of the node
console.log(node.nodeName); // Name of the node
console.log(node.nodeValue); // Value of the node (usually null for element nodes)
console.log(node.textContent); // Text content of the node

// Node methods
const newNode = document.createElement("span");
newNode.textContent = "New content";
node.appendChild(newNode); // Append new node as a child

const clonedNode = node.cloneNode(true); // Clone the node deeply
document.body.appendChild(clonedNode);// Append the cloned node to the document

Example

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
    <h1 id="heading">Welcome to CodingKoleji</h1>
    <div id="exampleNode"></div>
    <script>
      const node = document.getElementById("exampleNode");

      // Node properties
      console.log(node.nodeType); // Type of the node
      console.log(node.nodeName); // Name of the node
      console.log(node.nodeValue); // Value of the node (usually null for element nodes)
      console.log(node.textContent); // Text content of the node
      
      // Node methods
      const newNode = document.createElement("span");
      newNode.textContent = "New content";
      node.appendChild(newNode); // Append new node as a child
      
      const clonedNode = node.cloneNode(true); // Clone the node deeply
      document.body.appendChild(clonedNode);// Append the cloned node to the document
    </script>
  </body>
</html>

DOM nodes form the backbone of web page structure and content, enabling powerful and dynamic manipulation of documents through JavaScript.

Let's learn about DOM Collections in the next chapter.