The DOM (Document Object Model) is a programming interface for HTML and XML documents. It represents the structure of a document as a tree, where each HTML element (text, images, links, etc.) is a manipulable node. The DOM thus allows programming languages, like JavaScript, to access and dynamically modify the structure, style, and content of a web page.
<html> element is the entry point of the DOM tree.<body>, <div>, etc.), forming a hierarchical structure.<p>) is also considered as a distinct node.JavaScript allows access to DOM elements through methods that target tags according to their identifier, class, tag, or CSS selector. Here are the most common methods:
document.getElementById("id"): selects a unique element by its identifier.document.getElementsByClassName("class"): selects all elements having a specific class.document.getElementsByTagName("tag"): selects all elements of a certain tag type.document.querySelector("selector"): selects the first element matching a CSS selector.document.querySelectorAll("selector"): selects all elements matching a CSS selector.// Selection of an element by ID
let title = document.getElementById("title");
console.log(title.textContent);
Once an element is selected, JavaScript allows modifying its content, attributes, and style.
.textContent or .innerHTML.setAttribute("attribute", "value").style.property = "value"// Change the text of an element
title.textContent = "New Title";
// Modify an attribute
title.setAttribute("class", "new-class");
// Change style
title.style.color = "blue";
JavaScript also allows dynamically adding or removing elements in the DOM.
document.createElement("tag")parentElement.appendChild(newElement)parentElement.removeChild(childElement)// Create a new <p> element and add it to the <div> with ID "container"
let newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph.";
document.getElementById("container").appendChild(newParagraph);
// Remove an existing element
document.getElementById("container").removeChild(newParagraph);
Events allow triggering actions in response to user interactions, such as a click or mouse hover.
.addEventListener("event", function)// Add an event listener to the button to display an alert on click
let button = document.getElementById("myButton");
button.addEventListener("click", function() {
alert("Button clicked!");
});
DOM manipulation with JavaScript is essential for creating interactive web pages. By accessing and modifying DOM elements, it is possible to dynamically transform the content, structure and style of web pages, thus offering a better user experience.