Understanding and working with the Document Object Model in JavaScript
DOM (Document Object Model) manipulation is a crucial part of JavaScript that allows you to dynamically change the content, structure, and style of a web page.
JavaScript provides several methods to select elements from the DOM:
// Select by ID
const element = document.getElementById("myId");
// Select by class name
const elements = document.getElementsByClassName("myClass");
// Select by tag name
const paragraphs = document.getElementsByTagName("p");
// Select using CSS selectors
const element = document.querySelector(".myClass");
const elements = document.querySelectorAll("div.myClass");
Once you've selected an element, you can modify its content, attributes, and styles:
// Change text content
element.textContent = "New text content";
// Change HTML content
element.innerHTML = "New HTML content";
// Change attributes
element.setAttribute("class", "newClass");
// Change styles
element.style.color = "red";
element.style.fontSize = "20px";
You can also create new elements and add them to the DOM, or remove existing elements:
// Create a new element
const newElement = document.createElement("div");
newElement.textContent = "This is a new element";
// Add the new element to the DOM
document.body.appendChild(newElement);
// Remove an element
const elementToRemove = document.getElementById("removeMe");
elementToRemove.parentNode.removeChild(elementToRemove);
DOM manipulation often involves responding to user events:
const button = document.getElementById("myButton");
button.addEventListener("click", function() {
console.log("Button clicked!");
});