JavaScript DOM Manipulation
Connect JS to your HTML. Learn how to select, modify, and create HTML elements dynamically using the Document Object Model.
The Document Object Model (DOM)
When a web page is loaded, the browser creates a Document Object Model of the page. The HTML DOM model is constructed as a tree of Objects. With the object model, JavaScript gets all the power it needs to create dynamic HTML.
Selecting Elements
To manipulate HTML elements, you first need to find them.
document.getElementById("id")document.querySelector(".class")- Returns the first matching element.document.querySelectorAll("div")- Returns a NodeList of all matches.
Modifying Elements
Once selected, you can change content, styles, or attributes.
const heading = document.querySelector("#main-title");
// Change Text
heading.textContent = "New Title";
// Change HTML
heading.innerHTML = "<span>Styled Title</span>";
// Change Style
heading.style.color = "blue";
// Modify Classes
heading.classList.add("active");Creating Elements
You can create brand new elements and append them to the page dynamically.
const newPara = document.createElement("p");
newPara.textContent = "I was created via JS!";
document.body.appendChild(newPara);