What is DOM Manipulation?
DOM (Document Object Model) manipulation allows you to dynamically change the structure, style, and content of a webpage using JavaScript. Instead of just displaying static content, you can make your website interactive and responsive to user actions.
Selecting Elements
Before you can modify the DOM, you need to select the elements you want to work with. Here are some common methods:
document.getElementById()
: Selects an element by its unique ID.document.getElementsByClassName()
: Selects all elements with a specific class name.document.querySelector()
: Selects the first element that matches a CSS selector.document.querySelectorAll()
: Selects all elements that match a CSS selector.
// Example: Change the text content of an element with the ID "myElement"
let myElement = document.getElementById("myElement");
if (myElement) {
myElement.textContent = "New Text!";
}
Modifying Attributes
You can also modify attributes of HTML elements, such as changing their values or removing them.
// Example: Change the 'href' attribute of a link
let link = document.querySelector("a");
if (link) {
link.href = "https://www.example.com";
}
Adding and Removing Elements
You can dynamically add or remove HTML elements from the page.
// Example: Add a new paragraph element
let newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph!";
document.body.appendChild(newParagraph);
// Example: Remove an element
let elementToRemove = document.getElementById("elementToRemove");
if (elementToRemove) {
document.body.removeChild(elementToRemove);
}