JavaScript Tutorial in Hindi #25 | DOM Manipulation (2025)

✅ 1. What is DOM (Document Object Model)?

  1. The DOM is a programming interface for HTML and XML documents.
  2. It represents the page so that programs can change the document structure, style, and content.
  3. Think of it as a tree of nodes — each element, attribute, and text is a node.

✅ 2. Accessing Elements in DOM

  1. Using ID:
js
CopyEdit
let element = document.getElementById("myId");
  1. Using Class (returns collection):
js
CopyEdit
let elements = document.getElementsByClassName("myClass");
  1. Using Tag Name (returns collection):
js
CopyEdit
let items = document.getElementsByTagName("p");
  1. Using Query Selector (first match):
js
CopyEdit
let firstBtn = document.querySelector("button");
  1. Using Query Selector All (all matches):
js
CopyEdit
let allBtns = document.querySelectorAll("button");

✅ 3. Manipulating Content and Attributes

  1. Change content:
js
CopyEdit
element.textContent = "Hello World!";
element.innerHTML = "<strong>Hello World!</strong>";
  1. Change attributes:
js
CopyEdit
element.setAttribute("src", "image.jpg");
let href = element.getAttribute("href");
element.removeAttribute("disabled");
  1. Change styles:
js
CopyEdit
element.style.color = "red";

✅ 4. Adding & Removing Elements

  1. Create and add new element:
js
CopyEdit
let newDiv = document.createElement("div");
newDiv.textContent = "I am new!";
document.body.appendChild(newDiv);
  1. Remove element:
js
CopyEdit
let toRemove = document.getElementById("oldElement");
toRemove.remove();

✅ 5. DOM Events (Basic Intro)

Events allow interaction by listening to user actions like clicks or key presses.

  1. Add event listener:
js
CopyEdit
let btn = document.querySelector("button");
btn.addEventListener("click", function() {
alert("Button clicked!");
});

✅ 6. Common Interview Questions on DOM

🔸 What is the DOM?

🔸 How do you access elements in the DOM?

🔸 Difference between innerText, textContent, and innerHTML.

🔸 How do you add and remove DOM elements?

🔸 What is event bubbling and event capturing?

🔸 How to attach events to dynamically created elements?

🔸 What are some common DOM methods?