DOM Manipulation in JavaScript

Extended DOM Manipulation

What is DOM?

DOM Topics

DOM in Detail

DOM stands for Document Object Model. It is a programming interface for HTML and XML documents. It represents the page so that programs can change the structure, style, and content of a document dynamically.

Why Use DOM?

How Does DOM Work?

The browser parses HTML and builds a tree-like structure known as the DOM tree. JavaScript can then use this structure to access and modify elements using the document object.

Why document is an Object?

In JavaScript, everything is an object. The document is a global object provided by the browser that represents the entire HTML page. It has properties and methods to interact with and manipulate the page.

What Can DOM Do?

Targeting Elements in DOM

We use various methods on document to access HTML elements:

1. getElementById()

Targets a single element by its ID.

const title = document.getElementById("main-title");

2. getElementsByClassName()

Returns a collection of all elements with the given class name.

const items = document.getElementsByClassName("item");

3. getElementsByTagName()

Returns a collection of elements with the specified tag (like <p>, <div>).

const paragraphs = document.getElementsByTagName("p");

4. querySelector()

Returns the first element that matches a CSS selector.

const firstItem = document.querySelector(".item");

5. querySelectorAll()

Returns all elements that match a CSS selector.

const allItems = document.querySelectorAll(".item");

Example: Change Text Content

// HTML: <h1 id="header">Hello</h1>
const header = document.getElementById("header");
header.textContent = "Welcome to DOM";

Example: Add Event Listener

// HTML: <button id="clickBtn">Click Me</button>
document.getElementById("clickBtn").addEventListener("click", function() {
  alert("Button Clicked!");
});

References