JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript DOM Nodes


What Are DOM Nodes?

In JavaScript, the DOM (Document Object Model) is represented as a tree of nodes. A node is a single point in this tree. Every part of an HTML document—elements, text, comments, and even the document itself—is considered a node.

Understanding nodes is essential for traversing, manipulating, or interacting with the DOM, especially when working with dynamic content.

Types of DOM Nodes

There are several types of nodes in the DOM:

  1. Element Node (nodeType = 1) – Represents an HTML element like <div> or <p>.

  2. Text Node (nodeType = 3) – Represents the text inside an element.

  3. Comment Node (nodeType = 8) – Represents comments in HTML.

  4. Document Node (nodeType = 9) – Represents the whole document.

  5. DocumentFragment Node (nodeType = 11) – A lightweight container used for temporary DOM structures.

Accessing Node Properties

Every node has useful properties:

let element = document.querySelector(".myDiv");

console.log("Node name:", element.nodeName); // Returns the tag name (DIV)
console.log("Node type:", element.nodeType); // Returns 1 for element node
console.log("Parent node:", element.parentNode); // Access parent
console.log("Child nodes:", element.childNodes); // Access all child nodes including text
console.log("First child:", element.firstChild); // First child node
  • nodeName – Returns the tag name for element nodes or #text for text nodes.

  • nodeType – Returns a numeric value indicating the node type.

  • childNodes – Returns a NodeList of all child nodes, including text and comment nodes.

Accessing Element vs Text Nodes

Element Nodes Only

let element = document.querySelector(".myDiv");

console.log(element.children); // HTMLCollection of element nodes only
console.log(element.firstElementChild); // First child element
console.log(element.lastElementChild);  // Last child element
  • Use children or firstElementChild to ignore text nodes.

Text Nodes

let textNode = document.querySelector(".myDiv").firstChild;
console.log(textNode.nodeName); // #text
console.log(textNode.nodeValue); // Actual text content
  • nodeValue gives the text content of text nodes.

  • Text nodes often represent whitespace between elements.

Creating New Nodes

You can create nodes dynamically and add them to the DOM:

// Create a new element node
let newDiv = document.createElement("div");
newDiv.textContent = "Hello, I am a new div!";
newDiv.style.backgroundColor = "lightgreen";

// Append to body
document.body.appendChild(newDiv);

// Create a text node separately
let textNode = document.createTextNode("This is a text node.");
newDiv.appendChild(textNode);
  • createElement – Creates a new element node.

  • createTextNode – Creates a text node.

  • appendChild – Adds the node as a child of another node.

Inserting Nodes

You can insert nodes before or after existing nodes:

let parent = document.querySelector(".container");
let newNode = document.createElement("p");
newNode.textContent = "Inserted paragraph";

// Insert before the first child
parent.insertBefore(newNode, parent.firstChild);
  • insertBefore(newNode, referenceNode) inserts newNode before referenceNode.

  • Useful for dynamic content insertion in lists, tables, or menus.

Removing Nodes

let removeDiv = document.querySelector(".removeMe");

// Remove the node from DOM
removeDiv.parentNode.removeChild(removeDiv);
  • Always use parentNode to remove a child node.

  • Prevents orphan nodes in the DOM tree.

Replacing Nodes

let oldNode = document.querySelector(".old");
let newNode = document.createElement("div");
newNode.textContent = "I replaced the old node";

oldNode.parentNode.replaceChild(newNode, oldNode);
  • replaceChild(newNode, oldNode) replaces oldNode with newNode.

  • Useful for updating content dynamically without removing all children manually.

Node Properties for Traversal

DOM nodes have several properties for navigating the tree:

  • parentNode – Access the parent node.

  • childNodes – Access all child nodes (elements, text, comments).

  • firstChild / lastChild – Access the first or last child node.

  • previousSibling / nextSibling – Access siblings (all node types).

  • previousElementSibling / nextElementSibling – Access siblings that are elements only.

let node = document.querySelector(".child");
console.log(node.nextElementSibling); // Next element node
console.log(node.nextSibling);        // Next node (may be text)

Practical Example: Dynamic Node Manipulation

<div class="container">
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
</div>
let container = document.querySelector(".container");

// Create a new paragraph node
let newPara = document.createElement("p");
newPara.textContent = "I am dynamically added!";

// Insert before the second paragraph
container.insertBefore(newPara, container.children[1]);

// Remove the first paragraph after 3 seconds
setTimeout(() => {
    container.removeChild(container.firstElementChild);
}, 3000);
  • Demonstrates creating, inserting, and removing nodes dynamically.

  • Useful for interactive UI updates, like notifications, chat messages, or lists.

Best Practices

  • Use children and firstElementChild when you only need element nodes.

  • Use childNodes when you need to access text and comment nodes as well.

  • Always check for existence of nodes before modifying them to avoid errors.

  • Use createElement, createTextNode, insertBefore, and replaceChild for dynamic DOM manipulation.

  • Avoid unnecessary deep traversal for better performance.

Summary of the Tutorial

JavaScript DOM Nodes are the building blocks of the DOM tree. Key points:

  • Nodes represent elements, text, comments, or the document itself.

  • Use nodeName, nodeType, childNodes, parentNode to inspect and traverse nodes.

  • You can create, insert, replace, and remove nodes dynamically.

  • DOM Nodes are essential for manipulating content, building interactive UIs, and handling dynamic data.

Mastering DOM Nodes allows you to manipulate the DOM efficiently and build flexible, dynamic web applications.


Practice Questions

  1. Select an element and log its nodeName and nodeType to the console.

  2. Access a parent node of a selected element and change its background color.

  3. Loop through all childNodes of a container and log the node type of each.

  4. Create a new <div> element with some text and append it to the body.

  5. Create a text node separately and append it to an existing <p> element.

  6. Insert a new <li> element before the second item in a list using insertBefore.

  7. Remove a specific child node from its parent element using removeChild.

  8. Replace an existing node with a new element using replaceChild.

  9. Access the next and previous siblings of a selected node and change their styles.

  10. Check if a node has any child nodes and log a message depending on the result.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top