DOM manipulation means using JavaScript to find elements on a page and change them — their text, their HTML content, their styling, or their classes. This builds directly on the introduction to the DOM; this post covers the actual methods you'll use most often in real code.
Selecting Elements
Before you can change anything, you need a reference to the element. querySelector and querySelectorAll are the modern, most flexible way to do this — they accept any valid CSS selector:
<!-- HTML -->
<ul id="fruit-list">
<li class="item">Apple</li>
<li class="item">Banana</li>
</ul>
// One element — the first match
const list = document.querySelector("#fruit-list");
// All matching elements — returns a NodeList, not an array
const items = document.querySelectorAll(".item");
console.log(items.length); // 2
console.log(items[0].textContent); // "Apple"
Output:
2
Apple
getElementById("fruit-list") and getElementsByClassName("item") are older alternatives that still work, but querySelector/querySelectorAll are preferred today since they accept any CSS selector, not just IDs or class names.
Changing Content: innerHTML vs textContent
These two properties look similar but behave very differently:
const list = document.querySelector("#fruit-list");
// textContent treats the value as plain text — safe, no HTML parsing
list.textContent = "<b>Mango</b>"; // literally shows the tags as text
// innerHTML parses the string as real HTML
list.innerHTML = "<li>Mango</li>"; // actually creates a new <li> element
innerHTML is powerful but should never be set using untrusted user input directly — doing so opens the door to XSS (cross-site scripting) attacks, since any <script> tags in the string could run. When you're only inserting plain text, textContent is both safer and slightly faster.
Changing Styles and Classes
const heading = document.querySelector("h1");
// Direct inline style
heading.style.color = "crimson";
heading.style.fontSize = "2rem";
// Preferred for anything more than a one-off change: toggle a CSS class
heading.classList.add("highlight");
heading.classList.remove("highlight");
heading.classList.toggle("highlight"); // adds it if missing, removes it if present
In real projects, classList is usually the better approach — it keeps your styling logic in CSS where it belongs, and JavaScript just flips classes on and off. Combine this with event listeners and you have everything needed to build an interactive UI, like a button that toggles a menu open and closed.
