JavaScript DOM Manipulation - Basics and Examples
The Document Object Model (DOM) represents the structure of a web page and allows you to manipulate its content using JavaScript. In this guide, we'll cover the basics of DOM manipulation and provide examples to help you get started.
Accessing Elements
You can access elements in the DOM using JavaScript by selecting them with methods like getElementById
, querySelector
, or getElementsByClassName
:
<!-- HTML -->
<div id="myDiv">This is a div</div>
// JavaScript
let divElement = document.getElementById("myDiv");
console.log(divElement.textContent); // Outputs: "This is a div"
Modifying Elements
You can change the content, attributes, and style of elements using JavaScript:
let paragraph = document.querySelector("p");
// Change text content
paragraph.textContent = "New text content";
// Add a CSS class
paragraph.classList.add("highlight");
// Modify attributes
paragraph.setAttribute("data-custom", "example");
Creating Elements
You can create new elements and add them to the DOM dynamically:
let newElement = document.createElement("div");
newElement.textContent = "Newly created element";
let container = document.getElementById("container");
container.appendChild(newElement);
Event Handling
You can attach event listeners to elements to respond to user interactions:
let button = document.getElementById("myButton");
button.addEventListener("click", function() {
alert("Button clicked!");
});
Removing Elements
You can remove elements from the DOM using the removeChild
method:
let elementToRemove = document.getElementById("toRemove");
let parentElement = elementToRemove.parentNode;
parentElement.removeChild(elementToRemove);
Conclusion
JavaScript DOM manipulation is a crucial skill for web development. With the ability to access, modify, create, and remove elements, you can create dynamic and interactive web pages. Start experimenting with DOM manipulation to build engaging web applications.
Happy coding!