JavaScriptBasicsbeginner

JavaScript DOM Manipulation for Beginners

Learn what the DOM is, how to select elements, change text, styles and classes, create elements and handle clicks, then build a small task list page.

Published
TL;DR – Quick Answer

The DOM (Document Object Model) is the browser's tree of objects that represents your HTML page. JavaScript changes the page by changing this tree. First select an element, for example with document.getElementById("title") or document.querySelector(".card"). Then change it: set textContent to change text, use style or classList to change the look, and use createElement and appendChild to add new elements. To react to the user, attach an event listener such as addEventListener("click", handler).

On This Page

HTML builds a page and CSS styles it, but the page stays the same until something changes it. JavaScript is that something. When you click "Add to cart" and the cart count goes up, or a form shows "Email is required" in red, JavaScript is changing the page through the DOM.

This page explains what the DOM is, then covers the four skills you need most: selecting elements, changing text and styles, creating elements and handling clicks. It ends with one small page that uses all four. You should know basic HTML (see our HTML tutorial) and basic JavaScript variables and functions. Try every example in our online HTML, CSS and JS editor.

What is the DOM?

When the browser loads an HTML page, it builds a tree of objects from it. This tree is the Document Object Model, or DOM. Every tag becomes a node in the tree.

This HTML:

<body>
  <h1>Hello</h1>
  <ul>
    <li>Java</li>
    <li>SQL</li>
  </ul>
</body>

becomes this tree:

document
  └── html
        └── body
              ├── h1  ("Hello")
              └── ul
                    ├── li  ("Java")
                    └── li  ("SQL")

JavaScript reaches the tree through the document object. When your code changes a node, the browser redraws that part of the page. Your HTML file on disk does not change; only the live page in the browser does.

Where to put your script

Your script must run after the elements it uses exist. The simplest way is to put the <script> tag just before </body>:

<body>
  <h1 id="title">Hello</h1>

  <script src="app.js"></script>
</body>

Another common way is <script src="app.js" defer></script> inside <head>. defer tells the browser to run the script only after the whole page has been read.

Common mistake: Putting a plain <script> in the <head> and calling document.getElementById("title"). The h1 does not exist yet, so you get null, and the next line fails with "Cannot read properties of null".

Step 1: Select elements

Method Returns Example
document.getElementById("id") One element, or null document.getElementById("title")
document.querySelector("css selector") The first match, or null document.querySelector(".card")
document.querySelectorAll("css selector") A list of all matches document.querySelectorAll("li")
document.getElementsByClassName("name") A live list of matches document.getElementsByClassName("card")

querySelector and querySelectorAll accept any CSS selector, so they are the most flexible:

const title = document.getElementById("title");     // id="title"
const sameTitle = document.querySelector("#title"); // same element
const firstCard = document.querySelector(".card");  // first class="card"
const items = document.querySelectorAll("ul li");   // every li inside a ul

items.forEach((item) => {
  console.log(item.textContent);
});

Note the # and . in querySelector, just like in CSS. getElementById takes the id without #.

Step 2: Change text and HTML

getElementById example: change the text

<h1 id="title">My tasks</h1>
<script>
  const title = document.getElementById("title");
  title.textContent = "Today's tasks";
</script>

The heading now reads "Today's tasks".

textContent vs innerHTML

const box = document.querySelector("#box");

box.textContent = "<b>Hi</b>";   // shows the characters <b>Hi</b> as plain text
box.innerHTML = "<b>Hi</b>";     // shows Hi in bold
Property Treats the string as Safe for user input?
textContent Plain text Yes
innerHTML HTML markup No

Security note: Never put text typed by a user into innerHTML. Someone could type HTML that runs their own JavaScript on your page. This attack is called XSS (cross-site scripting). Use textContent for anything a user typed.

Change attributes

const img = document.querySelector("img");
img.src = "logo-dark.png";
img.alt = "Company logo";

const link = document.querySelector("a");
link.setAttribute("href", "https://example.com");

const input = document.querySelector("#email");
console.log(input.value);   // what the user typed in the input

For form fields, read and set .value, not textContent.

Step 3: Change style and classes

Inline style

const title = document.getElementById("title");
title.style.color = "darkblue";
title.style.backgroundColor = "#eef4ff";
title.style.fontSize = "32px";

CSS property names with a dash become camelCase in JavaScript: background-color becomes backgroundColor, font-size becomes fontSize.

classList (usually better)

Instead of setting many styles in JavaScript, define a class in CSS and add or remove it:

.highlight {
  background-color: yellow;
  font-weight: bold;
}
const card = document.querySelector(".card");
card.classList.add("highlight");      // add the class
card.classList.remove("highlight");   // remove it
card.classList.toggle("highlight");   // add if missing, remove if present
card.classList.contains("highlight"); // true or false

This keeps all the design in your CSS file and makes the JavaScript short. It is the approach most real projects use.

Step 4: Create and remove elements

const list = document.querySelector("#taskList");

const li = document.createElement("li");  // 1. create
li.textContent = "Revise arrays";          // 2. fill
list.appendChild(li);                      // 3. add to the page

li.remove();                               // remove it again

The new element does not appear on the page until you add it to the tree with appendChild (or append or prepend).

Step 5: Handle events

An event is something that happens on the page: a click, a key press, a form submit, the mouse moving over an element. You react to events with addEventListener:

const button = document.querySelector("#greetBtn");

button.addEventListener("click", () => {
  alert("Hello!");
});

The arrow function runs every time the button is clicked. If arrow functions are new to you, read JavaScript arrow functions explained.

Event When it fires
click The element is clicked
input The value of an input changes, on every key press
change An input, select or checkbox value is committed (for example, after leaving the field)
submit A form is submitted
keydown A key is pressed
mouseover The mouse moves onto the element

The event object

The browser passes an event object to your function. It tells you what happened:

const form = document.querySelector("form");

form.addEventListener("submit", (event) => {
  event.preventDefault();                 // stop the page from reloading
  console.log("Form submitted");
});

document.addEventListener("keydown", (event) => {
  console.log("You pressed " + event.key);
});

event.preventDefault() stops the browser's default action. For a form, that action is sending the data and reloading the page, which you usually do not want when JavaScript handles the form.

Common mistake: Writing button.addEventListener("click", sayHello()) with brackets. That calls sayHello immediately, once, and passes its return value instead of the function. Write sayHello without brackets, or wrap it: () => sayHello().

Put it together: a small task list page

This page lets you type a task, add it to a list, and click a task to mark it done. It uses every step above.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Task List</title>
  <style>
    .done { text-decoration: line-through; color: gray; }
  </style>
</head>
<body>
  <h1 id="title">My tasks</h1>
  <p id="count">Total tasks: 0</p>

  <input id="taskInput" type="text" placeholder="Type a task">
  <button id="addBtn">Add task</button>

  <ul id="taskList"></ul>

  <script>
    const input = document.getElementById("taskInput");
    const addBtn = document.getElementById("addBtn");
    const list = document.getElementById("taskList");
    const count = document.getElementById("count");

    function updateCount() {
      const total = list.querySelectorAll("li").length;
      count.textContent = "Total tasks: " + total;
    }

    addBtn.addEventListener("click", () => {
      const text = input.value.trim();
      if (text === "") {
        input.style.borderColor = "red";
        return;
      }
      input.style.borderColor = "";

      const li = document.createElement("li");
      li.textContent = text;

      li.addEventListener("click", () => {
        li.classList.toggle("done");
      });

      list.appendChild(li);
      input.value = "";
      updateCount();
    });
  </script>
</body>
</html>

What happens when you use it:

  1. Click Add task with an empty box: the input border turns red and nothing is added.
  2. Type "Revise arrays" and click Add task: a new list item appears, the box clears and the count shows "Total tasks: 1".
  3. Add "Practise SQL joins": the count shows "Total tasks: 2". Extra spaces around the text are removed by trim().
  4. Click "Revise arrays" in the list: it gets a line through it and turns grey. Click again to undo.

After steps 1 to 4, the list in the DOM looks like this:

<ul id="taskList">
  <li class="done">Revise arrays</li>
  <li>Practise SQL joins</li>
</ul>

How each part maps to the steps:

Code Step
getElementById(...) Select elements
count.textContent = ... Change text
input.style.borderColor, classList.toggle("done") Change style and classes
createElement("li"), appendChild(li) Create elements
addEventListener("click", ...) Handle events

The task text goes in with textContent, not innerHTML, so even if someone types HTML tags, they appear as plain text.

Ideas to extend it

  1. Add a Delete button inside each task that removes it with li.remove().
  2. Let the user press Enter to add a task by listening for keydown and checking event.key === "Enter".
  3. Show "No tasks yet" when the list is empty.
  4. Save tasks in localStorage so they stay after a page refresh.

When pages have many moving parts, updating the DOM by hand gets complicated. Libraries like React manage the DOM for you; our React tutorial is the natural next step once these basics feel easy.

Quick revision

  • The DOM is the browser's live tree of your HTML.
  • Select with getElementById, querySelector and querySelectorAll.
  • Change text with textContent; avoid innerHTML for user input.
  • Change looks with style or, better, classList.
  • Add elements with createElement and appendChild.
  • React to the user with addEventListener.

To check your understanding, go through the JavaScript DOM and events interview questions.

Frequently Asked Questions

What is the DOM in JavaScript?
The DOM is a tree of objects the browser builds from your HTML. Each tag becomes a node in the tree. JavaScript can read and change these nodes, and the browser updates the page on screen to match.
What is the difference between getElementById and querySelector?
getElementById finds one element by its id. querySelector takes any CSS selector, such as #title, .card or ul li, and returns the first match. querySelectorAll returns every match.
What is the difference between textContent and innerHTML?
textContent sets or reads plain text. innerHTML reads or sets HTML markup, so tags inside the string become real elements. Never put user input into innerHTML, because it can run harmful code.
How do I handle a button click in JavaScript?
Select the button and call addEventListener with "click" and a function: button.addEventListener("click", () => { ... }). The function runs every time the button is clicked.
Why does getElementById return null?
Usually because the script runs before the element exists. Put your script tag just before the closing body tag, or add the defer attribute to the script tag in the head. A typo in the id also causes null.

Want to Build Your Career in Java Full Stack with AI?

Join CodeBegun and train with working industry engineers — Discover CodeBegun's Java Full Stack track

Apply for Demo Class →
Siva Prasad Galaba
Founder, CodeBegun · Staff Engineer

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaches Java, Spring Boot and system design the way the industry actually works, and mentors students through projects, mock interviews and placement preparation.

Technically reviewed by CodeBegun Technical TeamLast reviewed 5 December 2026 LinkedIn
Chat with us