JavaScript DOM Manipulation Tutorial - Select, Create, Update Elements
JavaScript DOM Manipulation
The DOM, or Document Object Model, is the browser's object representation of an HTML page. JavaScript uses the DOM to find elements, read content, change styles, update attributes, create new elements, remove elements, and react to user actions.
If HTML is the structure and CSS is the presentation, DOM manipulation is how JavaScript changes the page after it has loaded.
Selecting Elements
Use querySelector() to select the first matching element and querySelectorAll() to select all matching elements. These methods use CSS selectors, so the same selector ideas you use in CSS work in JavaScript.
const heading = document.querySelector("h1");
const saveButton = document.querySelector("#saveBtn");
const cards = document.querySelectorAll(".card");
console.log(heading.textContent);
console.log(cards.length);
Changing Text and HTML
Use textContent when you want to write plain text. Use innerHTML only when you intentionally want to parse an HTML string. Never put untrusted user input into innerHTML, because that can create cross-site scripting security issues.
const message = document.querySelector("#message");
message.textContent = "Saved successfully";
const list = document.querySelector("#todoList");
list.innerHTML = "<li>Learn DOM</li><li>Practice events</li>";
Changing Attributes
Attributes such as href, src, alt, disabled, and aria-* can be read or updated from JavaScript. For common properties, direct property access is usually clean and readable.
const link = document.querySelector("#docsLink");
link.href = "https://developer.mozilla.org/";
link.textContent = "Read MDN Docs";
const image = document.querySelector("#profilePhoto");
image.src = "/images/user.png";
image.alt = "User profile photo";
const submitButton = document.querySelector("#submitBtn");
submitButton.disabled = true;
submitButton.setAttribute("aria-busy", "true");
Changing Classes and Styles
Use classList to add, remove, toggle, or check CSS classes. This is usually better than writing many inline styles because CSS remains responsible for visual design.
const panel = document.querySelector(".panel");
panel.classList.add("is-open");
panel.classList.remove("is-hidden");
panel.classList.toggle("is-active");
if (panel.classList.contains("is-open")) {
console.log("Panel is visible");
}
// Use inline styles only for dynamic one-off values.
panel.style.maxHeight = "300px";
Creating and Adding Elements
Create elements with document.createElement(), set their content and attributes, then insert them with append(), prepend(), before(), or after().
const list = document.querySelector("#todoList");
const item = document.createElement("li");
item.className = "todo-item";
item.textContent = "Practice DOM manipulation";
list.append(item);
Removing and Replacing Elements
Use remove() to delete an element and replaceWith() to replace one element with another. Always check that an element exists before trying to modify it.
const oldAlert = document.querySelector(".alert");
if (oldAlert) {
oldAlert.remove();
}
const loading = document.querySelector("#loading");
const done = document.createElement("p");
done.textContent = "Data loaded";
if (loading) {
loading.replaceWith(done);
}
Reading Form Values
Forms are one of the most common places where DOM manipulation is used. Use value for input values, checked for checkboxes, and FormData when you want to read many fields from a form.
const form = document.querySelector("#profileForm");
form.addEventListener("submit", function (event) {
event.preventDefault();
const formData = new FormData(form);
const name = formData.get("name");
const email = formData.get("email");
console.log({ name, email });
});
Events and DOM Updates
DOM manipulation becomes powerful when combined with events. A user clicks, types, submits, scrolls, or focuses something; JavaScript responds by updating the DOM.
const countText = document.querySelector("#count");
const increaseButton = document.querySelector("#increaseBtn");
let count = 0;
increaseButton.addEventListener("click", function () {
count += 1;
countText.textContent = count;
});
Performance Best Practices
const list = document.querySelector("#users");
const users = ["Asha", "Ravi", "Maya", "Dev"];
const fragment = document.createDocumentFragment();
users.forEach(function (name) {
const item = document.createElement("li");
item.textContent = name;
fragment.append(item);
});
list.append(fragment);
Common DOM Mistakes
- The DOM is the browser object model for the HTML document.
- Use querySelector and querySelectorAll to find elements with CSS selectors.
- Use textContent for plain text and be careful with innerHTML.
- Use classList for visual state changes instead of writing many inline styles.
- Create elements with document.createElement and insert them with append, prepend, before, or after.
- DOM work is often combined with events to make pages interactive.
Level Up Your Javascript Skills
Master Javascript with these hand-picked resources