DOM Manipulation in JavaScript
Selecting elements, changing them, handling events — and the two mistakes that make a script do nothing at all.
5 minute read · Free · Taught properly in our Front End Development Training in Amritsar
The DOM is the browser's live model of the page. JavaScript changes the page by changing that model.
Selecting
document.querySelector("#total"); // first match, by CSS selector
document.querySelectorAll(".card"); // all matches
Two functions cover nearly everything. They take any CSS selector you already know: #id, .class, nav a, input[type="email"].
Changing
const box = document.querySelector("#total");
box.textContent = "4500"; // text
box.classList.add("is-active"); // classes
box.classList.toggle("open");
box.style.color = "crimson"; // inline style
box.setAttribute("aria-hidden", "true");
Prefer textContent over innerHTML. innerHTML parses whatever you give it as HTML, so putting user input through it is how cross-site scripting happens. Use it only for markup you wrote yourself.
Events
document.querySelector("#save").addEventListener("click", (event) => {
event.preventDefault(); // stop a form submitting/navigating
console.log("saved");
});
For a list of items, do not attach a handler to every one. Attach one to the parent and check what was clicked:
list.addEventListener("click", (e) => {
const item = e.target.closest("li");
if (item) console.log(item.dataset.id);
});
That keeps working for items added later, which per-item handlers do not.
The two reasons nothing happens
1. The script ran before the element existed. A <script> in the <head> runs before the body is parsed, so querySelector returns null and the next line throws. Put the script at the end of the body, or add defer:
<script src="app.js" defer></script>
2. The selector does not match. querySelector("total") looks for a <total> tag; you meant "#total". When something is silently dead, console.log the result of the selector first. null tells you the problem is the selector, not your logic.
Try it
Paste any of this into our HTML playground — it runs in the page, so you can see the result immediately without setting up a project.
Stuck on this in your own code?
That is what a class is for. Sit one for free at WebPrims on Majitha Road, Amritsar — write some JavaScript, ask the mentor why yours is not working, and decide afterwards.