JavaScript HTML DOM Complete Guide

Understanding the Document Object Model and DOM Tree Structure

What is the DOM?

The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content.

DOM Characteristics:

  • Platform-independent interface
  • Tree structure representation
  • Programming interface for document manipulation
  • Live representation - changes update in real-time

What is the HTML DOM?

The HTML DOM is the specific DOM implementation for HTML documents. It defines HTML elements as objects with properties, methods, and events.

HTML DOM vs Browser DOM:

// HTML DOM - Document structure
document.getElementById('myElement');
document.querySelector('.my-class');

// Browser DOM (BOM) - Browser window
window.location;
window.history;
window.navigator;

The HTML DOM Tree of Objects

The DOM represents an HTML document as a tree structure where each node is an object representing a part of the document.

HTML Structure:




  My Page


  

Welcome


  

    

Hello World


    
  


DOM Tree Representation:

Document
└── html
   ├── head
   │   └── title
   │       └── "My Page"
   └── body
       ├── h1
       │   └── "Welcome"
       └── div class="container"
           ├── p
           │   └── "Hello World"
           └── button
               └── "Click me"

DOM Manipulation Demo

Live DOM Manipulation

Element 1
Element 2
Element 3
Click buttons to see DOM manipulation in action!

DOM Node Types

Common Node Types:

  • Element Node - HTML tags (div, p, span)
  • Text Node - Text content inside elements
  • Attribute Node - HTML attributes (class, id)
  • Comment Node - HTML comments
  • Document Node - The entire document
// Checking node types
const element = document.getElementById('myElement');
console.log(element.nodeType); // 1 (Element node)
console.log(element.nodeName); // "DIV"
console.log(element.nodeValue); // null

DOM Traversal Methods

Navigating the DOM Tree:

// Parent/Child relationships
const parent = element.parentNode;
const children = element.childNodes;
const firstChild = element.firstChild;
const lastChild = element.lastChild;

// Sibling relationships
const nextSibling = element.nextSibling;
const previousSibling = element.previousSibling;

DOM Query Methods

Finding Elements:

// Single element
const byId = document.getElementById('id');
const byQuery = document.querySelector('.class');

// Multiple elements
const byClass = document.getElementsByClassName('class');
const byTag = document.getElementsByTagName('div');
const byQueryAll = document.querySelectorAll('.class');

DOM Modification Methods

Changing the DOM:

// Creating elements
const newElement = document.createElement('div');
newElement.textContent = 'New element';

// Adding to DOM
parent.appendChild(newElement);
parent.insertBefore(newElement, referenceElement);

// Removing from DOM
parent.removeChild(element);