Modifying the Document in JavaScript

Modifying the Document in JavaScript

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

document.getElementById("demo").innerHTML = "<strong>Hello, World!</strong>"; document.getElementById("demo").textContent = "Hello, World!";

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

document.getElementById("myImage").src = "new-image.jpg"; document.getElementById("myLink").href = "https://example.com";

Using setAttribute

document.getElementById("myImage").setAttribute("alt", "New Image");

🔹 3. Changing CSS Styles (style, classList)

Example: Modifying styles directly

document.getElementById("box").style.backgroundColor = "blue"; document.getElementById("box").style.fontSize = "20px";

Example: Adding or removing CSS classes

document.getElementById("box").classList.add("highlight"); document.getElementById("box").classList.remove("hidden"); document.getElementById("box").classList.toggle("active"); // Toggles the class

🔹 4. Creating and Appending New Elements (createElement, appendChild)

Example: Creating a new paragraph

let newPara = document.createElement("p"); // Create a <p> element newPara.textContent = "This is a new paragraph."; // Set text document.body.appendChild(newPara); // Add to body

Example: Adding an item to a list

let li = document.createElement("li"); li.textContent = "New Item"; document.getElementById("myList").appendChild(li);

🔹 5. Removing Elements (removeChild, remove)

Example: Removing an element from the DOM

let element = document.getElementById("toRemove"); element.parentNode.removeChild(element);

or (modern approach):

document.getElementById("toRemove").remove();

🔹 6. Replacing Elements (replaceChild)

Example: Replacing a paragraph with a heading

let newHeading = document.createElement("h2"); newHeading.textContent = "This is a heading"; let oldPara = document.getElementById("oldPara"); oldPara.parentNode.replaceChild(newHeading, oldPara);

🔹 7. Inserting HTML (insertAdjacentHTML)

Example: Inserting HTML before an element

document.getElementById("container").insertAdjacentHTML("beforebegin", "<p>Before container</p>");

🔹 Positions Available:

PositionDescription
"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

let original = document.getElementById("box"); let clone = original.cloneNode(true); // `true` clones with child elements document.body.appendChild(clone);

🔹 9. Wrapping and Unwrapping Elements

Example: Wrapping an element inside a div

let wrapper = document.createElement("div"); wrapper.classList.add("wrapper"); let element = document.getElementById("content"); element.parentNode.insertBefore(wrapper, element); wrapper.appendChild(element);

Example: Unwrapping an element

let child = document.getElementById("content"); let parent = child.parentNode; parent.replaceWith(...parent.childNodes);

🔹 10. Modifying Multiple Elements (Looping)

Example: Changing all paragraphs' text color

document.querySelectorAll("p").forEach(p => { p.style.color = "blue"; });

Example: Adding a class to all list items

document.querySelectorAll("li").forEach(item => { item.classList.add("highlight"); });

📌 Summary

MethodPurpose
innerHTMLSet or get HTML content
textContentSet or get text content (safe from XSS)
setAttribute(name, value)Modify attributes like src, href, alt
.style.propertyChange inline styles
.classList.add/remove/toggleModify 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! 🎯

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close