Skip to the content

Lesson 87 of 296

The DOM: select and change elements

What you will learn

  • The DOM tree and node types
  • Selecting elements
  • Moving around the tree
  • Reading and changing text, HTML, attributes, classes and styles
  • Creating, inserting and removing elements
  • Updating the DOM efficiently and safely
On this page

The DOM tree

The DOM represents the page as a tree of nodes. The top is document. Each element is a node with a parent, children and siblings.

<ul id="menu">
  <li class="item">Home</li>
  <li class="item active">About</li>
</ul>
document
  html
    body
      ul#menu
        li.item       "Home"
        li.item.active "About"

Node types you will meet:

TypeExample
Element node<li>
Text nodeThe text "Home"
Comment node<!-- note -->
Document nodedocument

Selecting elements

MethodReturns
document.getElementById("menu")One element or null
document.querySelector(".item")The first match for a CSS selector, or null
document.querySelectorAll(".item")All matches, as a static NodeList
document.getElementsByClassName("item")All matches, as a live HTMLCollection
element.querySelector(...)Searches only inside that element

querySelector and querySelectorAll accept any CSS selector (Lesson 15):

document.querySelector("#menu li.active");
document.querySelectorAll("input[type='checkbox']:checked");

Static vs live lists

  • A static NodeList (from querySelectorAll) is a snapshot. It does not change when the page changes.
  • A live HTMLCollection (from getElementsByClassName, children) updates automatically. Looping over a live list while adding or removing matching elements can cause bugs.

NodeList has forEach. Neither has map or filter, so convert when needed:

const items = [...document.querySelectorAll(".item")];
const texts = items.map((li) => li.textContent);

Moving around the tree

PropertyGives
el.parentElementThe parent element
el.childrenChild elements (live)
el.firstElementChild / lastElementChildFirst / last child element
el.nextElementSibling / previousElementSiblingNext / previous sibling element
el.closest(".card")The nearest ancestor (or itself) matching a selector
el.matches(".active")true if the element matches the selector

closest is very useful with event delegation (Lesson 88).

Properties without "Element" (childNodes, nextSibling) also include text nodes, such as the spaces between tags, which surprises people.

Text and HTML content

PropertyReads or setsNotes
textContentAll text, including hidden elementsFast. Safe for user data: treats it as text.
innerTextOnly visible text, as it appearsSlower: it needs layout information
innerHTMLThe HTML inside the elementParses HTML. Dangerous with user data.
el.textContent = "Hello <b>Sam</b>";     shows the tags as literal text
el.innerHTML = "Hello <b>Sam</b>";       shows Sam in bold

innerHTML and XSS

If you put user-provided text into innerHTML, an attacker can inject HTML that runs JavaScript:

const name = '<img src="x" onerror="stealCookies()">';
greeting.innerHTML = `Hello ${name}`;       runs the attacker's code
greeting.textContent = `Hello ${name}`;     safe: shown as text

This attack is called XSS (Cross-Site Scripting, Part 20). Rule: use textContent for any text from users or APIs. If you must insert user HTML, clean it with a sanitiser library (such as DOMPurify) first.

Attributes

link.getAttribute("href");
link.setAttribute("href", "/about");
link.removeAttribute("target");
link.hasAttribute("download");

Common attributes also exist as properties: img.src, input.value, input.checked, button.disabled, a.href.

Attribute vs property for inputs: the value attribute is the starting value written in the HTML. The value property is the current value after the user types. Read input.value to get what the user typed.

data attributes

Custom data can be stored in data-* attributes and read with dataset:

<button data-product-id="42" data-action="add">Add</button>
button.dataset.productId     "42"   (always a string)
button.dataset.action        "add"

Hyphenated names become camelCase in dataset.

Classes

el.classList.add("active");
el.classList.remove("hidden");
el.classList.toggle("open");
el.classList.toggle("open", isOpen);      add if true, remove if false
el.classList.contains("active");
el.classList.replace("old", "new");

Prefer changing classes and keeping styles in CSS, over setting inline styles in JavaScript.

Inline styles

el.style.backgroundColor = "red";        CSS names become camelCase
el.style.setProperty("--brand", "teal"); CSS variables
getComputedStyle(el).width;              the final value after all CSS rules

el.style only reads inline styles. Use getComputedStyle to read the real value.

Creating and inserting elements

const li = document.createElement("li");
li.textContent = "Contact";
li.classList.add("item");

menu.append(li);             add at the end (accepts several nodes and strings)
menu.prepend(li);            add at the start
someEl.before(li);           insert before someEl
someEl.after(li);            insert after someEl
someEl.replaceWith(li);      replace someEl
li.remove();                 remove it
menu.replaceChildren();      remove all children

Older methods you will see: appendChild, insertBefore, removeChild.

insertAdjacentHTML("beforeend", html) adds HTML without destroying existing children. It has the same XSS risk as innerHTML.

Updating efficiently

Each change to the live DOM can trigger layout and paint. For many new elements, build them off the page first, then insert once:

const fragment = document.createDocumentFragment();
for (const product of products) {
  const li = document.createElement("li");
  li.textContent = product.name;
  fragment.append(li);
}
list.append(fragment);       one insert into the page

A DocumentFragment is a lightweight container that is not part of the page.

The template element

<template> holds HTML that is not rendered, to be copied by JavaScript:

<template id="row-template">
  <li class="row"><span class="name"></span><button>Remove</button></li>
</template>
const tpl = document.getElementById("row-template");
const row = tpl.content.cloneNode(true);
row.querySelector(".name").textContent = "Sam";
list.append(row);

Common mistakes

  • querySelector returns null because the script ran before the element existed (use defer), or the selector is wrong.
  • Using innerHTML with user data.
  • Expecting querySelectorAll results to have map.
  • Reading el.style.width and getting an empty string because the width comes from CSS.
  • Adding hundreds of elements one by one inside a loop.

How to say it in an interview

"The DOM is a tree of nodes representing the page. I select with querySelector and querySelectorAll, which return a static NodeList, and use closest to find ancestors. For text I use textContent, never innerHTML with user data, because that allows XSS. I store custom data in data attributes, toggle classes rather than set inline styles, and build many elements in a DocumentFragment or from a template before inserting them once, to limit reflows."

Key words

WordMeaning
NodeAny item in the DOM tree
ElementA node for an HTML tag
NodeListA list of nodes, static from querySelectorAll
HTMLCollectionA live list of elements
textContentThe text of an element, safe to set
innerHTMLThe HTML inside an element, parsed when set
XSSInjecting malicious script into a page
datasetAccess to data-* attributes
DocumentFragmentAn off-page container for building nodes

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.