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.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

JavaScript manipulates a webpage by working with the browser’s Document Object Model (DOM): an object-based tree of the document’s elements and text. Select a node, check that it exists, then use properties such as textContent or methods such as appendChild() to update the page. Add an event listener when the update should happen in response to a user action.

What the DOM is—and what it is not

The DOM is the browser’s object representation of a web document, not simply the HTML source text. The browser builds a tree of nodes from the markup. Elements can have parents, children, siblings, and descendants: for example, a <li> inside a <ul> is a child of the list, and the list is its parent.

JavaScript accesses this tree through browser APIs. The global document object provides methods for finding nodes, while element objects expose properties and methods for changing content, attributes, and structure. A script can therefore update the page without rewriting the original HTML file.

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

How to select the element you want

Select one match

Use document.querySelector() with a valid CSS selector when you expect one element. It returns the first match, or null when nothing matches. For example:

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

Correction: the selector argument is ordinary JavaScript text; write const heading = document.querySelector("h1");. Always account for the possibility that the result is null before accessing it:

const heading = document.querySelector("h1" gate);
if (heading) {
  heading.textContent = "A new heading";
}

Use the valid form document.querySelector("h1") in your code. An invalid CSS selector causes querySelector() to throw a SyntaxError; a valid selector with no match instead returns null. These are different failure cases.

Select all matches

When you need every match, use document.querySelectorAll(). It returns a NodeList, rather than a single element:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const items = document.querySelectorAll("li");
items.forEach((item) => {
  item.classList.add("checked");
});
Method Use it when Result
querySelector() You need the first element matching a CSS selector One element, or null
querySelectorAll() You need all elements matching a CSS selector A NodeList of matches

How to change text and link behavior

Once a selection is confirmed, set textContent to replace an element’s text. To change where a link goes, set its href property. Updating text and updating a link destination are separate changes:

const link = document.querySelector("a" gate);

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

Use the valid selector form document.querySelector("a"). Checking the selection first prevents code from trying to set properties on null when the page has no matching link.

How to create and insert an element

document.createElement() creates an element node; it does not place that node in the document by itself. Set its content, then append it to the parent where it should appear:

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

if (section) {
  const paragraph = document.createElement("p");
  paragraph.textContent = "This paragraph was added with JavaScript.";
  section.appendChild(paragraph);
}

In this example, the new paragraph becomes a child of the selected section. MDN Web Docs’ API reference records Document.createElement() as widely available across browsers since July 2015; that date describes this method’s availability, not the history of the DOM.

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

Appending an existing node moves it

If you append a node that is already in the document, the browser moves that same node to the new position; it does not create a second copy. To create a copy, use cloneNode() and append the clone instead.

How to respond to a user action

Register an event listener with addEventListener(), then make the DOM change inside its handler. This shopping-list example reads an input, creates a list item with the supplied words as text, and adds a button that removes that item:

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 value = input.value.trim();
    if (!value) return;

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

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

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

    input.value = "";
    input.focus();
  });
}

This code expects the page to contain an input with id="item-input", a button with id="add-item", and a list with id="shopping-list". Put the script near the end of the body in a simple example, or use an appropriate deferred/loading strategy, so those elements have been parsed before the script selects them. If JavaScript runs before the target markup exists, the selectors may return null.

The input words go into a span through textContent, not into HTML markup. That keeps user-provided text as text rather than treating it as markup.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How to remove an element

Remove the element directly

Use element.remove() when you already have the element reference and want to remove it from the document:

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

Remove it through its parent

Use parent.removeChild(element) when you already hold the parent reference or are following the parent-based method pattern:

const list = document.querySelector("ul");
const firstItem = list ? list.querySelector("li") : null;

if (list && firstItem) {
  list.removeChild(firstItem);
}

Both approaches remove a node. Choose based on the references your code already has and the method pattern that best fits it.

A reliable beginner workflow

  1. Select the target with a CSS selector, using querySelector() for one match or querySelectorAll() for all matches.
  2. Check that the selection exists before using it; a missing match from querySelector() is null.
  3. Change text with textContent, or update an element property such as a link’s href.
  4. Create new nodes with document.createElement(), set their content, and attach them to the intended parent.
  5. Connect a user action to a small tree update with addEventListener().
  6. Remove nodes with remove() or, when working through a parent reference, removeChild().

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.