Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / JavaScript Tutorial / Chapter 4: DOM Manipulation & Events
JAVASCRIPT ⏱ 14 min read

DOM Manipulation: Selecting & Modifying Elements

The DOM (Document Object Model) is JavaScript's doorway into your HTML page, allowing you to change text, HTML, and attributes dynamically.

What is it?

The DOM is a tree-like object representation of the HTML document created by the browser. JavaScript uses the `document` object to query, create, modify, and delete nodes.

Why is it used?

Enables interactive features like live search results, dynamically added cards, updated counters, and toggled modals.

Detailed Explanation

DOM Methods: • Selecting Elements: • `document.getElementById('id')`: Fastest lookup by ID. • `document.querySelector('css-selector')`: Finds first matching element. • `document.querySelectorAll('css-selector')`: Finds all matching elements (returns NodeList). • Modifying Elements: • `el.textContent`: Safely updates text content (prevents XSS attacks). • `el.innerHTML`: Parses string as HTML (use cautiously). • `el.setAttribute('attr', 'val')` / `el.getAttribute('attr')`. • Creating & Appending: • `document.createElement('tag')`. • `parent.appendChild(child)` or `parent.append(child)`. • `el.remove()`: Removes element from the DOM.

Syntax Structure

Syntax Blueprint
const btn = document.querySelector('.btn-primary');
btn.textContent = 'Updated Label';
const newDiv = document.createElement('div');
parent.appendChild(newDiv);

Code Example

JAVASCRIPT Code
<!-- Conceptual HTML -->
<!-- <ul id="courseList"></ul> -->

// Dynamic DOM Generation
const courses = ["Python", "Excel", "Data Science", "C++"];
const listContainer = document.getElementById("courseList");

// Create list items dynamically
courses.forEach(courseName => {
  const li = document.createElement("li");
  li.className = "course-item";
  li.textContent = courseName;
  
  // Add a delete button inside
  const deleteBtn = document.createElement("button");
  deleteBtn.textContent = "×";
  deleteBtn.onclick = () => li.remove();
  
  li.appendChild(deleteBtn);
  listContainer.appendChild(li);
});

Explanation of the Code

• Iterates over course array. • Creates `<li>` elements, adds class, sets text safely via `.textContent`. • Adds an interactive delete button that removes the element when clicked.

Expected Output

The unordered list is dynamically populated with courses and interactive delete buttons.

Real-World Application

Used across todo apps, e-commerce cart line-items, and live chat message feeds.

Common Mistakes to Avoid

• Using `.innerHTML` with untrusted user input, introducing Cross-Site Scripting (XSS) vulnerabilities. Always prefer `.textContent` for text. • Trying to call array methods on a NodeList before converting with `Array.from()` or `querySelectorAll().forEach()`.

Quick Practice Challenge

Select an element with id 'status' and update its text content to 'Connected' and its color to green.

Key Takeaways

• Use `querySelector` and `querySelectorAll` with standard CSS selectors. • Always prefer `textContent` over `innerHTML` to prevent security vulnerabilities. • Create elements using `document.createElement()` and mount with `appendChild()`.