Modifying the Document in JavaScript (DOM Manipulation)
JavaScript allows you to dynamically modify the Document Object Model (DOM) to change, add, or remove elements and attributes on a webpage.
🔹 1. Changing HTML Content (innerHTML
, textContent
)
You can modify the content inside an element using:
innerHTML
→ Can insert HTML content (not safe from XSS).textContent
→ Inserts only text (safer, doesn’t parse HTML).
✔ Example: Changing content dynamically
✅ Use textContent
when inserting user input to prevent XSS attacks.
🔹 2. Changing Element Attributes (setAttribute
, .src
, .href
)
Modify attributes like src
, href
, id
, class
, etc.
✔ Example: Changing an image source
✔ Using setAttribute
🔹 3. Changing CSS Styles (style
, classList
)
✔ Example: Modifying styles directly
✔ Example: Adding or removing CSS classes
🔹 4. Creating and Appending New Elements (createElement
, appendChild
)
✔ Example: Creating a new paragraph
✔ Example: Adding an item to a list
🔹 5. Removing Elements (removeChild
, remove
)
✔ Example: Removing an element from the DOM
or (modern approach):
🔹 6. Replacing Elements (replaceChild
)
✔ Example: Replacing a paragraph with a heading
🔹 7. Inserting HTML (insertAdjacentHTML
)
✔ Example: Inserting HTML before an element
🔹 Positions Available:
Position | Description |
---|---|
"beforebegin" | Inserts before the element itself |
"afterbegin" | Inserts inside, before first child |
"beforeend" | Inserts inside, after last child |
"afterend" | Inserts after the element itself |
🔹 8. Cloning Elements (cloneNode
)
✔ Example: Cloning an element
🔹 9. Wrapping and Unwrapping Elements
✔ Example: Wrapping an element inside a div
✔ Example: Unwrapping an element
🔹 10. Modifying Multiple Elements (Looping)
✔ Example: Changing all paragraphs' text color
✔ Example: Adding a class to all list items
📌 Summary
Method | Purpose |
---|---|
innerHTML | Set or get HTML content |
textContent | Set or get text content (safe from XSS) |
setAttribute(name, value) | Modify attributes like src , href , alt |
.style.property | Change inline styles |
.classList.add/remove/toggle | Modify CSS classes |
createElement(tag) | Create a new element |
appendChild(node) | Append element to a parent |
removeChild(node) , .remove() | Remove an element |
replaceChild(newNode, oldNode) | Replace an element |
insertAdjacentHTML(position, html) | Insert HTML at specific position |
cloneNode(true/false) | Clone an element |
🚀 Mastering these techniques will help you dynamically update your web pages! 🎯