DOM Manipulation

What is the DOM?

DOM Meaning

The DOM (Document Object Model) is a programming interface that represents an HTML or XML document as a tree structure where each node is an object.

In simple words:

The DOM connects web pages to programming languages like JavaScript, allowing you to change the page dynamically.

Structure of the DOM

  • The whole web page becomes a tree of nodes.
  • Each HTML element (like <h1>, <p>, <div>) is a node in the tree.
  • There are different types of nodes:
  • Document node (the root, entire page)
  • Element nodes (tags like <p>, <img>)
  • Text nodes (text inside elements)
  • Attribute nodes (like class=”title”)

Example: Simple HTML Page and DOM

HTML:

<!DOCTYPE html>
<html>
<body>
<h1>Hello World</h1>
<p>Welcome to the DOM.</p>
</body>
</html>

DOM Tree:

Document
└── html
└── body
├── h1
│ └── “Hello World”
└── p
└── “Welcome to the DOM.”

The DOM turns HTML into a structure that JavaScript can read and manipulate.

How JavaScript Interacts with the DOM

You can use JavaScript to:

  • Select elements (getElementById, querySelector, etc.)
  • Change content (element.textContent, element.innerHTML)
  • Change styles (element.style.color = “red”)
  • Add or remove elements (appendChild, removeChild)
  • Handle events (clicks, typing, scrolling)

Example: Changing Text Using the DOM

<h1 id=”title”>Hello</h1>

<script>
const heading = document.getElementById(“title”);
heading.textContent = “Hello, DOM World!”;
</script>

The <h1> content changes when the script runs.

Why the DOM is Important

  • Dynamic updates without reloading the page.
  • Interactive websites (like buttons, forms, pop-ups).
  • Control over structure, style, and content of a webpage.

Without the DOM, JavaScript could not manipulate HTML and webpages would be static.

Quick Summary:

Topic Explanation
DOM Definition Interface that represents HTML/XML pages as trees
DOM Purpose Connects web pages with programming languages
DOM Structure Tree with nodes (Document, Element, Text, Attribute)
JavaScript Role Access and change elements dynamically

Selecting elements (getElementById, querySelector, etc.)

Why Select Elements?

Selecting elements means grabbing HTML elements using JavaScript so you can read, change, or manipulate them.
You can modify text, style, attributes, or even react to user actions like clicks.

Common Methods to Select Elements

1. GetElementById()

  • Purpose: Selects one element with a specific id.
  • Returns: A single element (or null if not found).
  • Fastest method for selecting.

Syntax:

const element = document.getElementById(“elementId”);

Example:

<h1 id=”main-title”>Welcome!</h1>

const title = document.getElementById(“main-title”);
console.log(title.textContent); // “Welcome!”

Tip: IDs must be unique on a page.

2. getElementsByClassName()

  • Purpose: Selects all elements with a specific class name.
  • Returns: An HTMLCollection (looks like an array but not exactly).

Syntax:

const elements = document.getElementsByClassName(“className”);

Example:

<p class=”info”>Info 1</p>
<p class=”info”>Info 2</p>

const infoItems = document.getElementsByClassName(“info”);
console.log(infoItems.length); // 2

Access with index infoItems[0], infoItems[1].

3. getElementsByTagName()

  • Purpose: Selects all elements of a specific tag (like p, div, h1).
  • Returns: An HTMLCollection.

Syntax:

const paragraphs = document.getElementsByTagName(“p”);

Example:

<p>Paragraph 1</p>
<p>Paragraph 2</p>

const allParagraphs = document.getElementsByTagName(“p”);
console.log(allParagraphs.length); // 2

4. querySelector()

  • Purpose: Selects the first element that matches a CSS selector.
  • Returns: A single element (or null if none found).
  • Very powerful and flexible.

Syntax:

const element = document.querySelector(“selector”);

Example:

<div class=”box”>Box 1</div>
<div class=”box”>Box 2</div>

const firstBox = document.querySelector(“.box”);
console.log(firstBox.textContent); // “Box 1”

CSS Selectors: IDs (#id), classes (.class), tags (div), attributes ([type=”text”]).

5. querySelectorAll()

  • Purpose: Selects all elements that match a CSS selector.
  • Returns: A NodeList (can use forEach).

Syntax:

const elements = document.querySelectorAll(“selector”);

Example:

<p class=”highlight”>First</p>
<p class=”highlight”>Second</p>

const highlights = document.querySelectorAll(“.highlight”);
highlights.forEach(item => console.log(item.textContent));

HTMLCollection vs. NodeList

Feature HTMLCollection NodeList
Returned by getElementsByClassName, getElementsByTagName querySelectorAll
Live Update Yes (updates if DOM changes) No (static snapshot)
forEach() Method (needs conversion) (direct use)

Choosing the Right Method

Situation Best Method
Need single element by ID getElementById()
Need elements by class name or tag getElementsByClassName(),
getElementsByTagName()
Need first match by CSS selector querySelector()
Need all matches by CSS selector querySelectorAll()

Real Example – Full Flow

HTML:

<h1 id=”site-title”>Hello</h1>
<p class=”description”>First paragraph.</p>
<p class=”description”>Second paragraph.</p>

JavaScript:

const title = document.getElementById(“site-title”);
const descriptions = document.getElementsByClassName(“description”);
const firstParagraph = document.querySelector(“.description”);
const allParagraphs = document.querySelectorAll(“.description”);

console.log(title.textContent); // Hello
console.log(descriptions.length); // 2
console.log(firstParagraph.textContent); // First paragraph.
allParagraphs.forEach(p => console.log(p.textContent));

Quick Summary:

In JavaScript, you can select elements using methods like getElementById, querySelector, getElementsByClassName, and querySelectorAll to manipulate or interact with the page easily.

Changing content and styles

Why Change Content and Styles?

Using JavaScript, you can dynamically update:

  • Text
  • HTML structure
  • CSS styles

This makes websites interactive, dynamic, and user-friendly — no page reload needed!

Changing Content

There are several ways to change the content of HTML elements:

1. Text Content

  • Sets or gets the text inside an element.
  • Ignores HTML tags, treats everything as plain text.

Syntax:

element.textContent = “New Text Here”;

HTML:

<p id=”greet”>Hello!</p>

JavaScript:

const greet = document.getElementById(“greet”);
greet.textContent = “Welcome to the site!”;

Result: Only text is inserted.

2. Inner HTML

  • Sets or gets the HTML content inside an element.
  • Allows HTML tags inside.

Syntax:

element.innerHTML = “<strong>Bold Text</strong>”;

Example:

<div id=”content”></div>

JavaScript:

const content = document.getElementById(“content”);
content.innerHTML = “<h2>New Heading</h2><p>New paragraph!</p>”;

  • Result: HTML structure is rendered inside the div.
  • Warning: Using innerHTML can open security risks (like XSS attacks) if you insert untrusted content.

Handling events (click, input, submit)

Handling Events in JavaScript

JavaScript allows you to handle user interactions (events) like clicks, inputs, and form submissions to make web pages dynamic. Events are triggered by user actions, such as clicking a button or typing in a text box, and JavaScript listens for these events to execute a function.

There are many types of Handling Events in JavaScript.

1. Event Types

  • Click: Triggered when a user clicks an element (e.g., button, link).
  • Input: Triggered when a user types into a text field or textarea.
  • Submit: Triggered when a user submits a form.

2. Attaching Event Listeners

Method 1: Using addEventListener()

The addEventListener() method attaches an event handler to an element. It’s flexible and allows multiple event listeners for the same event.

Example – Handling a Click Event:

<button id=”myButton”>Click Me</button>

<script>
const button = document.getElementById(‘myButton’);
button.addEventListener(‘click’, function() {
alert(‘Button clicked!’);
});
</script>

Example – Handling Input Event:

<input type=”text” id=”myInput” placeholder=”Type something”>

<script>
const input = document.getElementById(‘myInput’);
input.addEventListener(‘input’, function() {
console.log(‘User typed: ‘ + input.value);
});
</script>

Example – Handling Submit Event:

<form id=”myForm”>
<input type=”text” name=”name”>
<button type=”submit”>Submit</button>
</form>

<script>
const form = document.getElementById(‘myForm’);
form.addEventListener(‘submit’, function(event) {
event.preventDefault(); // Prevent default form submission
console.log(‘Form submitted!’);
});
</script>

3. Event Propagation (Bubbling and Capturing)

  • Event Bubbling: Events propagate from the target element up to the root.
  • Event Capturing: Events propagate from the root to the target element.

You can control propagation with stopPropagation() and stopImmediatePropagation().

button.addEventListener(‘click’, function(event) {
event.stopPropagation(); // Prevents the event from bubbling up
});

4. Handling Multiple Events on the Same Element

You can use addEventListener() for multiple events. For instance, to handle both click and input.

element.addEventListener(‘click’, function() {
console.log(‘Clicked!’);
});

element.addEventListener(‘input’, function() {
console.log(‘Input changed!’);
});

5. Event Object

Every event handler receives an event object, which contains useful information like the target element, event type, and more.

button.addEventListener(‘click’, function(event) {
console.log(event.target); // Element that triggered the event
console.log(event.type); // Event type (e.g., ‘click’)
});

Summary:

Event handling in JavaScript allows developers to create interactive web pages by listening for user actions (e.g., clicks, inputs, and submits) and responding with custom functions. Methods like addEventListener() provide flexibility, while event propagation and the event object offer control and detailed information about the event.

Creating and Removing Elements Dynamically

JavaScript allows you to create, insert, modify, and remove HTML elements dynamically, enabling you to build highly interactive and real-time updating web pages.

Creating Elements

You can create a new HTML element using document.createElement():

const newDiv = document.createElement(‘div’); // Create a new <div> element
newDiv.textContent = ‘Hello, World!’; // Add text inside the div
newDiv.classList.add(‘greeting’); // Add a class
document.body.appendChild(newDiv); // Append it to the body

Key Methods:

  • document.createElement(tagName): Creates a new element.
  • element.textContent = ‘…’: Adds text inside an element.
  • element.classList.add(className): Adds CSS classes.
  • element.setAttribute(name, value): Sets attributes like id, href, etc.
  • parent.appendChild(element): Inserts the new element into the DOM.

Inserting at Specific Positions

  • parent.appendChild(child): Adds at the end.
  • parent.prepend(child): Adds at the beginning.
  • parent.insertBefore(newNode, referenceNode): Inserts before a specified node.

const referenceNode = document.getElementById(‘reference’);
document.body.insertBefore(newDiv, referenceNode);

Removing Elements

To remove an element:

  • Modern way: element.remove()
  • Old way: parent.removeChild(child)

const element = document.getElementById(‘toRemove’);
element.remove(); // Direct removal

Or:

const parent = document.getElementById(‘parent’);
const child = document.getElementById(‘child’);
parent.removeChild(child);

Replacing Elements

Use replaceChild(newNode, oldNode):

const newHeading = document.createElement(‘h2’);
newHeading.textContent = ‘New Heading’;
document.body.replaceChild(newHeading, document.getElementById(‘oldHeading’));

Quick Summary:

In JavaScript, you can create elements with createElement(), insert them with appendChild() or prepend(), remove them using remove() or removeChild(), and replace existing elements with replaceChild(), giving you full control over the page structure dynamically.

Leave a Comment