DOM Manipulation 🌐The Document Object Model (DOM) represents the structure of an HTML document as a tree of objects. JavaScript allows you to interact with this structure to change the content, style, and structure of a webpage in real-time.
DOM manipulation refers to using JavaScript to access, modify, or remove elements from the HTML document. This can include tasks like changing text, adding or removing elements, modifying styles, and handling events.
To manipulate elements, you first need to select them. There are several ways to select elements in the DOM using JavaScript:
// Example 1: Selecting Elements
const elementById = document.getElementById("myElement"); // By ID
const elementsByClass = document.getElementsByClassName("myClass"); // By class
const elementsByTag = document.getElementsByTagName("div"); // By tag
const querySelector = document.querySelector(".myClass"); // By CSS selector
const querySelectorAll = document.querySelectorAll(".myClass"); // By CSS selector (all matching)
Once you select an element, you can change its content using properties like innerHTML or textContent.
// Example 2: Changing Content
document.getElementById("myElement").innerHTML = "New Content!";
document.getElementById("myElement").textContent = "New Text Content!";
You can also modify the style of elements using the style property:
// Example 3: Changing Styles
document.getElementById("myElement").style.color = "blue";
document.getElementById("myElement").style.backgroundColor = "lightyellow";
document.getElementById("myElement").style.fontSize = "20px";
Adding or removing elements can be done using createElement, appendChild, removeChild, and remove methods.
// Example 4: Adding/Removing Elements
const newElement = document.createElement("div");
newElement.textContent = "I am a new div!";
document.body.appendChild(newElement); // Add element to body
const elementToRemove = document.getElementById("removeMe");
elementToRemove.remove(); // Remove element
DOM manipulation also involves adding event listeners to elements, allowing users to interact with the page (e.g., clicking buttons, submitting forms).
// Example 5: Event Handling
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});
Click the button to see DOM manipulation in action!
getElementById, querySelector, and getElementsByClassName to select elements in the DOM.innerHTML or textContent.style property to change styles like color, background, and font-size.createElement, appendChild, and removeChild to manipulate the DOM tree.addEventListener to make elements interactive by responding to events like clicks or form submissions.querySelector and querySelectorAll for selecting elements using CSS selectors as they are more flexible and modern.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!