Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk5 min

Mastering JavaScript DOM Manipulation: A Beginner’s Guide

A practical introduction to the browser DOM, with examples for selecting elements, changing text and links, adding nodes, handling clicks, and removing content.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

JavaScript DOM manipulation lets you read and change the page a browser has built from HTML. You can select an element, update its text or properties, create and insert new elements, and respond to user actions—all by working with the browser’s Document Object Model (DOM).

This guide assumes you know basic HTML and CSS and are learning JavaScript fundamentals. The examples use standard browser APIs, so you can try them in a simple web page.

As an Amazon Associate I earn from qualifying purchases.

What the DOM is—and why JavaScript uses it

The DOM is the browser’s object-based representation of a web document. It is not the original HTML source text: after the browser parses the markup, it exposes the document as objects that JavaScript can inspect and change. The document object is your entry point to that page representation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Think of the DOM as a tree. An element such as <ul> can be a parent of several <li> child elements. Those children are siblings of one another, and each is a descendant of the list. These relationships matter because DOM methods often select, add, or remove nodes relative to another element.

How to select elements safely

Use document.querySelector() with a CSS selector to find the first matching element. It returns the element when there is a match, or null when there is none, so check the result before trying to change it.

const heading = document.querySelector("h1");

if (heading) {
  heading.textContent = "A new heading";
}

The selector must be valid CSS; an invalid selector causes a SyntaxError. For example, ".notice" selects the first element with the class notice, while "#main" selects the element with the ID main.

One match or all matches?

Choose the method according to how many elements you expect:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Method What it returns Use it when
querySelector(selector) The first matching element, or null You want one element
querySelectorAll(selector) A NodeList containing all matching elements You want to work with every match

For example, document.querySelectorAll(".task") gives you the matching task elements as a NodeList. If your code expects at least one result, still account for the possibility that there are no matches.

How to change text and element properties

Use textContent when you want to set an element’s text. Use the relevant element property when you need to change how an element behaves—for example, set a link’s href to change its destination.

const link = document.querySelector("a.help-link");

if (link) {
  link.textContent = "Read the setup guide";
  link.href = "/setup";
}

Changing textContent changes the text inside the element; setting href updates the link target. A property update does not create a new element: it changes the selected element already in the DOM.

How to create and add an element

document.createElement() creates a new element node, but it does not put that element on the page by itself. Give it content, then append it to a parent already in the document.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const section = document.querySelector("#updates");

if (section) {
  const paragraph = document.createElement("p");
  paragraph.textContent = "Your update is ready.";
  section.appendChild(paragraph);
}

Here, createElement("p") makes the paragraph, textContent supplies its words, and appendChild() places it at the end of the section’s child list. MDN describes Document.createElement() as widely available across browsers since July 2015; that date refers to this API, not to the DOM as a whole. See the MDN createElement() reference.

Appending an existing node moves it

If you append an element that is already in the document, the browser moves that same node to the new position. It does not make a second copy. If you need a copy, use cloneNode() and append the clone instead.

How to make DOM changes in response to a click

Register an event listener with addEventListener(), then perform the DOM update inside its handler. The following small shopping list lets a visitor add an item and delete it again. The user’s text is assigned with textContent, so it becomes text in the page rather than markup to be interpreted.

<label for="item-input">Shopping item</label>
<input id="item-input" type="text">
<button id="add-item" type="button">Add item</button>
<ul id="shopping-list"></ul>

<script>
  const input = document.querySelector("#item-input");
  const addButton = document.querySelector("#add-item");
  const list = document.querySelector("#shopping-list");

  if (input && addButton && list) {
    addButton.addEventListener("click", () => {
      const itemText = input.value.trim();
      if (!itemText) return;

      const item = document.createElement("li");
      const label = document.createElement("span");
      label.textContent = itemText;

      const deleteButton = document.createElement("button");
      deleteButton.type = "button";
      deleteButton.textContent = "Delete";
      deleteButton.addEventListener("click", () => item.remove());

      item.appendChild(label);
      item.appendChild(deleteButton);
      list.appendChild(item);

      input.value = "";
      input.focus();
    });
  }
</script>

Each click translates into a small tree update: create an <li>, add a text span and a delete button, then attach the new list item to the <ul>. The delete button’s listener removes that item when clicked. The input is cleared and focused again after a successful addition.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

This example uses addEventListener() rather than putting an inline event-handler attribute in the HTML. Keeping behavior in JavaScript makes it easier to find and maintain.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How to remove an element

For most current code, call remove() on the element itself:

const notice = document.querySelector(".notice");
if (notice) notice.remove();

If your code already has the parent reference, you can remove a known child through removeChild():

const parent = document.querySelector("#messages");
const message = document.querySelector(".message");

if (parent && message) {
  parent.removeChild(message);
}

Both approaches remove the node from the document. Use remove() when the target element is what you have; use removeChild() when the parent-child relationship is already part of your code.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Make sure the HTML exists before the script runs

If JavaScript runs before the browser has parsed the target markup, a selector may return null even though the element appears later in the HTML file. For a basic page, place the script near the end of the <body>, after the elements the code needs. Alternatively, use an appropriate deferred script-loading strategy so the markup is available before your code accesses it.

When a DOM update does not happen, check the selector spelling, confirm the target exists, and make sure the script runs after that markup is parsed. These checks address the most common beginner problems: selecting the wrong element, assuming a match exists, or running code too early.

A practical way to think about DOM manipulation

Most beginner DOM tasks follow the same sequence: find the relevant node, verify it exists, change its content or properties—or create a node—and connect the change to an event when a user action should trigger it. Understanding that sequence is more useful than memorizing isolated methods: each API call either finds a node, changes one, or updates the tree.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.