Frontend Development · Tutorial 8 of 9
DOM Manipulation with JavaScript: selecting, changing and creating elements
By the FUTEAC Team · 14 November 2026 · 10 min read · Beginner
In short
The DOM is the browser's live copy of your HTML, organised as a tree you can read and change with JavaScript. Select an element with document.querySelector, change it with textContent or classList, create new ones with document.createElement and add them with appendChild, and react to the user with addEventListener. The page updates at once, with no reload.
- The DOM is a tree, not the HTML file. Your HTML is the starting point. Once the browser loads it, JavaScript works on the live tree, and every change shows up immediately.
querySelectortakes a CSS selector. Anything you can target in a stylesheet, you can select in JavaScript:#shopping-list,.item,li:last-child.textContentis the safe default for changing text. It treats the new value as plain text. UseinnerHTMLonly when you deliberately want to insert HTML, and never with text typed by a user.- New elements are built, then attached.
document.createElement("li")makes an element that exists nowhere untilappendChildputs it on the page. - This tutorial feeds the JavaScript Essentials course (/course/javascript-essentials) and the DOM Manipulation (/skill/dom-manipulation) skill.
Before you start
What is the DOM, really?
Open any page and the browser turns its HTML into a tree. The <html> element is the root, <body> is a branch, and every heading, paragraph and list item is a leaf hanging off it. That tree is the DOM, short for Document Object Model.
Think of it like a family tree for the page. Each element knows its parent, its children and its siblings, and JavaScript can walk the tree, read any branch and rearrange it. The HTML file on disk never changes. Only the live tree in the browser changes, and the screen follows it at once.
How do you select an element?
You cannot change an element until you have hold of it. JavaScript gives you four main ways, and two of them cover almost everything a beginner needs.
document.getElementById("page-title") finds the one element with that id. It is fast and exact, but it only works when the element has an id.
document.querySelector("#shopping-list .item") takes any CSS selector and returns the first element that matches. document.querySelectorAll("#shopping-list .item") returns all of them, as a list you can count and loop over. If you know CSS selectors, you already know how to select elements.
const title = document.getElementById("page-title");
const firstItem = document.querySelector("#shopping-list .item");
const allItems = document.querySelectorAll("#shopping-list .item");
console.log(allItems.length); // 3Run this against a list with three items and allItems.length is 3. That is the count you will see again in the worked example below, so keep it in mind.
One detail that trips people up: querySelectorAll returns a snapshot. It records the elements that match right now and does not update later. getElementsByClassName, by contrast, returns a live collection that updates itself. In the test run for this tutorial, a querySelectorAll list captured before an item was added still reported a length of 3 afterwards, while the live collection reported the new count. Neither is wrong, but if your count looks stale, check which one you used.
How do you change what is on the page?
Once you hold an element, three properties do most of the work.
textContent replaces the text inside an element. classList adds, removes or toggles a class, which changes the styling through your CSS. style sets one CSS property directly on the element.
const title = document.getElementById("page-title");
title.textContent = "My shopping list (4 items soon)";
const firstItem = document.querySelector("#shopping-list .item");
firstItem.classList.add("done");
firstItem.style.color = "green";After those three lines run, the heading reads "My shopping list (4 items soon)", the first list item carries the class done, and its text turns green. The heading change was verified in the browser: title.textContent read back exactly as the new string.
Use textContent for text and classList for styling. Setting style directly is fine for one-off changes, but a class keeps the styling in your CSS where it belongs. And a warning worth remembering: innerHTML inserts raw HTML, so if the text came from a user typing in a box, innerHTML can run whatever they typed as code. textContent cannot. That is why it is the default here.
How do you create elements and add them?
A page that never changes is a poster. The interesting part is adding new content while the user watches. It takes three steps: create the element, fill it, attach it.
const li = document.createElement("li");
li.className = "item";
li.textContent = "Butter";
document.getElementById("shopping-list").appendChild(li);createElement("li") builds a list item that exists in memory only. Setting className and textContent fills it. appendChild attaches it as the last child of the list, and only then does it appear on the page.
In the verified test run, the list started with 3 items, this code ran, and a fresh querySelectorAll count came back as 4, with the last item reading "Butter". That is the whole pattern: create, fill, attach.
How do you remove an element?
Removal is the shortest step of all. Select the element, call remove() on it, and it is gone from the tree.
const first = document.querySelector("#shopping-list .item");
first.remove();In the test run, removing the first item after the append above brought the count back from 4 to 3. There is no undo, so if the element matters, check you selected the right one before you remove it. querySelector returns the first match, which is exactly what you want when the first item is the target, and exactly the bug when it is not.
How do you react to a click?
Nothing so far has waited for the user. addEventListener is what turns a static page into an interactive one: it says, when this event happens on this element, run this function.
let clicked = 0;
document.getElementById("add-btn").addEventListener("click", function () {
clicked++;
});In the test run, a simulated click on the button fired the handler exactly once: clicked went from 0 to 1. The pattern is always the same three parts: the element, the event name ("click"), and the function to run. Later tutorials build on this with "input", "submit" and keyboard events, and the shape never changes.
The wrong turn: "Cannot read properties of null"
Here is the error every beginner meets, usually on their first evening with the DOM. Put your script in the <head> of the page, before the HTML it touches, and the browser runs it before the button exists.
<head>
<script>
const btn = document.getElementById("add-btn");
btn.addEventListener("click", function () {});
</script>
</head>The browser runs that script while the page is still loading. getElementById("add-btn") finds nothing and returns null, and the next line fails with the exact error this tutorial's test run produced:
TypeError: Cannot read properties of null (reading 'addEventListener')Read it plainly: you tried to read addEventListener off null, which means the element was not there when the code ran. It is a timing problem, not a spelling problem. The fix is one of two moves. Put the <script> tag at the end of the <body>, after all the HTML, or add defer to the script tag so the browser waits for the HTML first:
<script src="app.js" defer></script>Either way, the rule is simple: never touch the DOM before the browser has built it. When you see this error, check where your script sits before you check anything else.
Putting it together: a shopping list that works
Here is the whole app, small enough to type out and complete enough to use. It is the exact code from the verified test run, with the button wired up at the end of the body where it belongs.
<h1 id="page-title">My shopping list</h1>
<ul id="shopping-list">
<li class="item">Bread</li>
<li class="item">Milk</li>
<li class="item">Eggs</li>
</ul>
<input id="new-item" type="text" value="Butter">
<button id="add-btn">Add item</button>
<p id="count"></p>const list = document.getElementById("shopping-list");
const input = document.getElementById("new-item");
const count = document.getElementById("count");
function updateCount() {
count.textContent =
document.querySelectorAll("#shopping-list .item").length + " items on the list";
}
document.getElementById("add-btn").addEventListener("click", function () {
const li = document.createElement("li");
li.className = "item";
li.textContent = input.value;
list.appendChild(li);
updateCount();
});
updateCount();Expected output, verified in the browser: the page loads showing "3 items on the list". Click Add item and "Butter" appears as the fourth item, and the count reads "4 items on the list". The pieces you have already met are all here: select, create, fill, attach, listen, update.
Try it yourself
Build a second list on the same page, a "done" list. Add a button next to each shopping item that moves it to the done list when clicked. That means one addEventListener per button, appendChild to the done list (appending an element that already exists moves it, it does not copy it), and updateCount on both lists. If the button appears but does nothing, check the console for the null error from the wrong-turn section above.
Common mistakes
- Selecting before the element exists. The script runs before the HTML loads,
getElementByIdreturnsnull, and the next line throwsTypeError: Cannot read properties of null. Move the script to the end of the body or adddefer. - Using
innerHTMLfor user text. Text typed into an input is code if you feed it toinnerHTML. UsetextContentunless you deliberately want HTML. - Forgetting that
querySelectorAllis a snapshot. You captured the list, added an item, and the old list still says 3. Re-run the query after the change, or use a live collection. - Creating an element and wondering why nothing appears.
createElementbuilds it in memory only. UntilappendChildattaches it to the page, it is invisible. Create, fill, attach, in that order. - Calling
remove()on the wrong element.querySelectorreturns the first match. If you meant the last item, say so:querySelector("#shopping-list li:last-child").
Frequently asked questions
What is the difference between querySelector and getElementById?
getElementById finds one element by its id and is the fastest option. querySelector takes any CSS selector, so it can find elements by class, attribute or position, and querySelectorAll finds all of them. Use the id version when you have an id, and the selector version for everything else.
Should I use textContent or innerHTML?
textContent for text, always, unless you specifically need to insert HTML. innerHTML parses the string as HTML, which is a security risk with user input and slower than plain text. Most beginner pages never need innerHTML at all.
Why does my querySelectorAll length not change after I add an item?
Because the list it returned is a static snapshot, fixed at the moment you called it. Call querySelectorAll again after the change to get the fresh count. If you need a list that updates itself, getElementsByClassName returns a live collection instead.
Where does addEventListener go, in the head or the body?
The code must run after the element exists. Put the script at the end of the body, or add defer to the script tag. A script in the head without defer runs too early and getElementById returns null.
Do I need a framework to change a page with JavaScript?
No. Everything in this tutorial is plain JavaScript in the browser, no library and no build step. Frameworks like React manage the same DOM updates for you at larger scale, but they are built on exactly these methods, so learning them first makes React easier later.
Follow the Frontend Developer Roadmap
Build modern, responsive websites and web apps with HTML, CSS, JavaScript and React. Free, step by step, at your pace.
View the Roadmap