What is JavaScript DOM


The Document Object Model (DOM) is a programming interface provided by browsers that allows JavaScript to interact with and manipulate the structure and content of web documents. It represents the document as a tree of objects, where each node corresponds to a part of the document (e.g., elements, attributes, text). Understanding the DOM is crucial for dynamically modifying web pages and creating interactive user experiences.

Key Concepts of the DOM

  1. Document Tree Structure

    • The DOM represents a web page as a tree structure, where each node represents a part of the page. The top of the tree is the document object, which contains other nodes like elements, attributes, and text.

    Example:

    <html> <head> <title>Example</title> </head> <body> <h1>Hello World</h1> <p>This is an example paragraph.</p> </body> </html>

    The corresponding DOM tree:

    document └── html ├── head │ └── title └── body ├── h1 └── p
  2. Nodes

    • Element Nodes: Represent HTML tags (e.g., <div>, <p>, <a>).
    • Text Nodes: Represent the text content within elements.
    • Attribute Nodes: Represent attributes of HTML elements (e.g., class, id, src).
    • Document Node: Represents the entire HTML document.
  3. Accessing Elements

    • JavaScript provides various methods to access and manipulate DOM elements:
    // Accessing elements by ID let header = document.getElementById('headerId'); // Accessing elements by class name let items = document.getElementsByClassName('itemClass'); // Accessing elements by tag name let paragraphs = document.getElementsByTagName('p'); // Querying elements with CSS selectors let mainTitle = document.querySelector('h1'); let allLinks = document.querySelectorAll('a');
  4. Manipulating Elements

    • JavaScript can be used to modify the content, attributes, and styles of DOM elements.
    // Changing text content let title = document.querySelector('h1'); title.textContent = 'New Title'; // Changing HTML content let paragraph = document.querySelector('p'); paragraph.innerHTML = 'Updated paragraph content. <strong>Bold text</strong>'; // Modifying attributes let link = document.querySelector('a'); link.href = 'https://new-url.com'; // Adding styles let div = document.querySelector('div'); div.style.backgroundColor = 'lightblue';
  5. Creating and Removing Elements

    • JavaScript can create new elements and add them to the DOM, or remove existing elements.
    // Creating a new element let newDiv = document.createElement('div'); newDiv.textContent = 'This is a new div'; // Adding the new element to the DOM document.body.appendChild(newDiv); // Removing an element let oldDiv = document.querySelector('div'); document.body.removeChild(oldDiv);
  6. Event Handling

    • JavaScript can handle user interactions and other events by adding event listeners to elements.
    // Adding an event listener let button = document.querySelector('button'); button.addEventListener('click', function() { alert('Button clicked!'); }); // Removing an event listener function handleClick() { alert('Button clicked!'); } button.addEventListener('click', handleClick); button.removeEventListener('click', handleClick);
  7. Traversing the DOM

    • JavaScript allows you to navigate the DOM tree to find related elements.
    // Accessing parent element let child = document.querySelector('p'); let parent = child.parentNode; // Accessing child elements let firstChild = parent.firstChild; let lastChild = parent.lastChild; // Accessing sibling elements let nextSibling = child.nextSibling; let previousSibling = child.previousSibling;

Practical Example

Here’s a practical example that demonstrates some of these DOM operations:

HTML:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>DOM Example</title> </head> <body> <h1 id="header">Welcome</h1> <p class="description">This is a paragraph.</p> <button id="changeTextButton">Change Text</button> <button id="addElementButton">Add Element</button> </body> </html>

JavaScript:

// Changing text content document.getElementById('changeTextButton').addEventListener('click', function() { document.getElementById('header').textContent = 'Text Changed!'; }); // Adding a new element document.getElementById('addElementButton').addEventListener('click', function() { let newElement = document.createElement('p'); newElement.textContent = 'A new paragraph!'; document.body.appendChild(newElement); });