JavaScript Tutorial in Hindi #25 | DOM Manipulation (2025)
✅ 1. What is DOM (Document Object Model)?
- The DOM is a programming interface for HTML and XML documents.
- It represents the page so that programs can change the document structure, style, and content.
- Think of it as a tree of nodes — each element, attribute, and text is a node.
✅ 2. Accessing Elements in DOM
- Using ID:
js
CopyEdit
let element = document.getElementById("myId");
- Using Class (returns collection):
js
CopyEdit
let elements = document.getElementsByClassName("myClass");
- Using Tag Name (returns collection):
js
CopyEdit
let items = document.getElementsByTagName("p");
- Using Query Selector (first match):
js
CopyEdit
let firstBtn = document.querySelector("button");
- Using Query Selector All (all matches):
js
CopyEdit
let allBtns = document.querySelectorAll("button");
✅ 3. Manipulating Content and Attributes
- Change content:
js
CopyEdit
element.textContent = "Hello World!";
element.innerHTML = "<strong>Hello World!</strong>";
- Change attributes:
js
CopyEdit
element.setAttribute("src", "image.jpg");
let href = element.getAttribute("href");
element.removeAttribute("disabled");
- Change styles:
js
CopyEdit
element.style.color = "red";
✅ 4. Adding & Removing Elements
- Create and add new element:
js
CopyEdit
let newDiv = document.createElement("div");
newDiv.textContent = "I am new!";
document.body.appendChild(newDiv);
- 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.
- 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?