Skip to main content

Frontend development · Beginner · 25 min

Select and change page elements with the DOM

By Padding · Updated 18 Nov 2026
Modern browsers · DOM Living Standard · Node.js 26.13.1 LTS · Playwright 1.65.1 · node:26 image

You will build a reading-list page whose script finds, changes, adds and removes elements, then renders the whole list from an array through a template and re-renders it when the array changes.

On this page

The DOM (Document Object Model) is the browser's live, in-memory version of your page. The HTML file is only the starting point: the browser reads it, builds a tree of element objects, and draws what is in that tree. A script can find those objects and change them, and the page on screen follows. Every frontend framework does this underneath; knowing the plain calls makes framework code, browser bugs and developer tools far easier to understand.

In this tutorial you build a small reading-list page and change it from a script, one technique per step: finding elements, changing their text safely, switching classes and data attributes, adding and removing elements, and stamping out rows from a <template>. You finish with a page that draws its list from an array of objects and draws it again whenever the array changes, which is the core idea behind React, Vue and Svelte.

The page is three small files with no framework to download, which also keeps it light on a low-end Android phone or a prepaid data bundle. Commands are shown for a Linux or macOS shell; on Windows, use WSL or create the files in your editor with the same contents.

Step 1 · Serve a small page

Make a demo folder and write the page. It lists three books as plain HTML and loads app.js as a JavaScript module (type="module"). Module scripts wait until the HTML has been parsed, so the script can find every element without extra code.

Bash
mkdir -p ~/dom-reading-list-demo
cd ~/dom-reading-list-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Reading list</title>
  <link rel="stylesheet" href="style.css">
  <script type="module" src="app.js"></script>
</head>
<body>
  <main>
    <h1>Reading list</h1>
    <p id="summary">3 books</p>
    <p id="last-added"></p>
    <ul id="books">
      <li class="book" data-id="1" data-status="read">Things Fall Apart by Chinua Achebe</li>
      <li class="book" data-id="2" data-status="reading">Weep Not, Child by Ngũgĩ wa Thiong'o</li>
      <li class="book" data-id="3" data-status="to-read">Half of a Yellow Sun by Chimamanda Ngozi Adichie</li>
    </ul>
  </main>
</body>
</html>
HTML
cat > style.css <<'CSS'
body { font-family: system-ui, sans-serif; color: #1b1f24; max-width: 40rem; margin: 2rem auto; padding: 0 1rem; }
.book { padding: 0.5rem 0; border-bottom: 1px solid #d9dce1; }
.book.is-read { color: #5a6270; text-decoration: line-through; }
.book.is-current { font-weight: 700; }
form { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: end; }
label { display: grid; gap: 0.25rem; }
input, button { font: inherit; padding: 0.4rem 0.6rem; }
CSS
cat > app.js <<'JS'
console.log('app.js loaded');
JS

The <meta charset="utf-8"> line matters for the second book: without it, a browser may show the ũ and ĩ in Ngũgĩ as garbled characters. The same goes for titles in Yoruba, Amharic, Arabic or any other script your readers use.

A module script will not load from a file:// address, because the browser applies the same cross-origin rules it uses for websites, and it also refuses a module served without a JavaScript content type. So the page needs a web server, even on your own machine. Write a short one with Node's built-in http module:

Bash
cd ~/dom-reading-list-demo
cat > serve.mjs <<'JS'
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { extname, join } from 'node:path';

const types = {
  '.html': 'text/html; charset=utf-8',
  '.css': 'text/css; charset=utf-8',
  '.js': 'text/javascript; charset=utf-8',
};
const port = Number(process.env.PORT ?? 8080);

createServer(async (req, res) => {
  const path = new URL(req.url, 'http://localhost').pathname;
  const file = path === '/' ? 'index.html' : path.slice(1);
  const type = types[extname(file)];
  if (!type || file.includes('..')) return res.writeHead(404).end('Not found');
  try {
    const body = await readFile(join(import.meta.dirname, file));
    res.writeHead(200, { 'content-type': type, 'cache-control': 'no-store' }).end(body);
  } catch {
    res.writeHead(404).end('Not found');
  }
}).listen(port, '127.0.0.1', () => console.log(`Serving on http://127.0.0.1:${port}`));
JS

It serves only .html, .css and .js files from the demo folder and its subfolders (later that includes node_modules, which is harmless on your own machine), listens only on your own machine (127.0.0.1), and tells the browser not to cache, so a reload always picks up your latest edit. Start it in a second terminal and leave it running for the rest of the tutorial:

Bash
cd ~/dom-reading-list-demo
node serve.mjs

Check it worked

The terminal running the server prints Serving on http://127.0.0.1:8080. Open that address in your browser: you see the Reading list heading, "3 books" and three titles, with Ngũgĩ spelt correctly. Open the developer tools (F12 in most desktop browsers) and choose the Console tab: it shows app.js loaded. If port 8080 is already in use, stop the server with Ctrl+C and start it with PORT=8081 node serve.mjs, then use that port in every address below.

Step 2 · Find elements with querySelector and querySelectorAll

Both methods take a CSS selector, the same text you would write in a stylesheet. document.querySelector() returns the first matching element, or null if nothing matches. document.querySelectorAll() returns every match as a NodeList, which you can loop over with for...of or forEach. Replace app.js:

Bash
cd ~/dom-reading-list-demo
cat > app.js <<'JS'
const summary = document.querySelector('#summary');
const books = document.querySelectorAll('#books .book');

books.forEach((li, index) => {
  console.log(`${index}: ${li.textContent}`);
});

summary.textContent = `Found ${books.length} books with querySelectorAll`;
JS

#summary selects by id, and #books .book selects every element with the class book inside the element with the id books. textContent reads an element's text, and assigning to it replaces that text. If a selector matches nothing, querySelector returns null and the next line fails with Cannot read properties of null; that error in the console almost always means a typo in the selector or an element that does not exist yet.

Check it worked

Reload the page. The second line now reads "Found 3 books with querySelectorAll", and the console lists 0: Things Fall Apart by Chinua Achebe down to 2: Half of a Yellow Sun by Chimamanda Ngozi Adichie. Now right-click the page and choose View Page Source: the source still says "3 books". The file never changed; only the live DOM did. The Elements (or Inspector) panel in the developer tools shows the live DOM, with your new text.

Step 3 · Set text safely with textContent, not innerHTML

Text from a user, a form or an API can contain characters that look like HTML. textContent always treats what you give it as plain text. innerHTML parses it as HTML, which means a user can inject elements, and an injected event handler attribute runs as code. This is cross-site scripting (XSS): someone else's script running on your page, with access to everything your page can see.

Add a line that shows a title someone typed, including a hostile <img> tag. Append to app.js:

Bash
cd ~/dom-reading-list-demo
cat >> app.js <<'JS'

const lastAdded = document.querySelector('#last-added');
const typedTitle = 'Purple Hibiscus <img src="x" onerror="alert(\'This code ran\')">';
lastAdded.textContent = `Last added: ${typedTitle}`;
JS

Check it worked

Reload. The paragraph shows the whole string as text, angle brackets and all, and nothing else happens. Now see the hole for yourself: in app.js, change lastAdded.textContent = to lastAdded.innerHTML =, save and reload. An alert saying "This code ran" appears, and the paragraph shows only "Last added: Purple Hibiscus" with a broken image after it. The browser tried to load the image x, failed, and ran the onerror attribute. Change the line back to textContent before you continue. Use innerHTML only for HTML you wrote yourself, never for anything a person or another system supplied.

Step 4 · Switch classes and data attributes

Each book already carries data-status in the HTML. Custom data-* attributes are the standard place to keep small bits of state on an element, and element.dataset reads and writes them: data-status becomes dataset.status, and a name with hyphens such as data-started-on becomes dataset.startedOn. element.classList adds, removes and toggles classes without touching the element's other classes. Append:

Bash
cd ~/dom-reading-list-demo
cat >> app.js <<'JS'

for (const li of books) {
  li.classList.toggle('is-read', li.dataset.status === 'read');
  li.classList.toggle('is-current', li.dataset.status === 'reading');
}

const current = document.querySelector('[data-status="reading"]');
current.dataset.startedOn = '2026-11-02';
console.log(current.outerHTML);
JS

classList.toggle(name, force) adds the class when force is true and removes it when false, so the class always matches the data. The CSS from the first step styles .is-read and .is-current; the script only decides which element gets which class. Keeping the look in CSS and the state in classes and data attributes means a designer can restyle the list without touching the script.

Check it worked

Reload. Things Fall Apart is grey and struck through, and Weep Not, Child is bold. The console shows the second book's full HTML ending in data-started-on="2026-11-02">, followed by its text: the script added that attribute, written with hyphens, from the camelCase startedOn.

Step 5 · Add and remove elements

document.createElement() makes a new element that is not on the page yet. You set its text, classes and data, then place it with append(), which adds it as the last child of another element. element.remove() takes an element off the page. Append:

Bash
cd ~/dom-reading-list-demo
cat >> app.js <<'JS'

const list = document.querySelector('#books');

const newBook = document.createElement('li');
newBook.className = 'book';
newBook.dataset.id = '4';
newBook.dataset.status = 'to-read';
newBook.textContent = 'Purple Hibiscus by Chimamanda Ngozi Adichie';
list.append(newBook);

list.querySelector('.is-read').remove();

summary.textContent = `${list.children.length} books on the page`;
JS

One detail catches people out: the NodeList that querySelectorAll returned in the earlier step is static. It is a snapshot taken when the line ran, so books still holds the three original items, including the removed one, and does not include Purple Hibiscus. Ask the DOM again (list.children or a fresh querySelectorAll) whenever you need the current state.

Check it worked

Reload. Things Fall Apart has gone, Purple Hibiscus is the last item, and the summary reads "3 books on the page". In the Elements panel, the new <li> carries data-id="4" and data-status="to-read".

Step 6 · Render the list from an array through a template

Changing elements one by one works for small tweaks, but it gets hard to follow once the page holds real data. The usual fix is to keep the data in an array of objects, treat it as the single source of truth, and write one render() function that draws the list from it.

A <template> element holds HTML that the browser parses but does not show. Its content property is a document fragment you can copy with cloneNode(true) (true means copy all the children as well), fill in, and add to the page. Replace index.html so the list starts empty, with a template for one row and a form you will wire up in the next step:

Bash
cd ~/dom-reading-list-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Reading list</title>
  <link rel="stylesheet" href="style.css">
  <script type="module" src="app.js"></script>
</head>
<body>
  <main>
    <h1>Reading list</h1>
    <p id="summary"></p>
    <form id="add-book">
      <label>Title <input name="title" required></label>
      <label>Author <input name="author" required></label>
      <button type="submit">Add book</button>
    </form>
    <p id="last-added"></p>
    <ul id="books"></ul>
  </main>

  <template id="book-row">
    <li class="book"><span class="title"></span> by <span class="author"></span></li>
  </template>
</body>
</html>
HTML

Then replace app.js with the data and the render function:

Bash
cd ~/dom-reading-list-demo
cat > app.js <<'JS'
const books = [
  { id: 1, title: 'Things Fall Apart', author: 'Chinua Achebe', status: 'read' },
  { id: 2, title: 'Weep Not, Child', author: "Ngũgĩ wa Thiong'o", status: 'reading' },
  { id: 3, title: 'Half of a Yellow Sun', author: 'Chimamanda Ngozi Adichie', status: 'to-read' },
];

const list = document.querySelector('#books');
const summary = document.querySelector('#summary');
const rowTemplate = document.querySelector('#book-row');

function render() {
  const rows = books.map((book) => {
    const row = rowTemplate.content.firstElementChild.cloneNode(true);
    row.dataset.id = book.id;
    row.dataset.status = book.status;
    row.classList.toggle('is-read', book.status === 'read');
    row.classList.toggle('is-current', book.status === 'reading');
    row.querySelector('.title').textContent = book.title;
    row.querySelector('.author').textContent = book.author;
    return row;
  });
  list.replaceChildren(...rows);

  const read = books.filter((book) => book.status === 'read').length;
  summary.textContent = `${books.length} books, ${read} read`;
}

window.readingList = { books, render };
render();
JS

render() builds one row per book with map, then replaceChildren() removes whatever the list held and appends the new rows in a single call. Every value goes in through textContent, so a title with angle brackets stays text, as you saw earlier. firstElementChild picks the <li> and skips the whitespace text around it inside the template.

Module scripts keep their variables to themselves, so window.readingList deliberately exposes the array and the function for you to try in the console in the next step. A real app would not need that line.

Check it worked

Reload. The page looks as it did before you added Purple Hibiscus, with Things Fall Apart struck through and Weep Not, Child in bold, but the HTML file no longer contains any books. The summary reads "3 books, 1 read". In the Elements panel, the <template> is still there with its row inside, and the three real rows sit in the <ul>.

Step 7 · Re-render when the array changes

Now the rule is simple: change the array, then call render(). Try it in the console first. Paste these lines one at a time and watch the page after each:

JavaScript
readingList.books[2].status = 'read';
readingList.render();
readingList.books.splice(0, 1);
readingList.render();

After the first render(), Half of a Yellow Sun is struck through and the summary says "3 books, 2 read". After the second, Things Fall Apart has gone. Changing the array alone does nothing visible; the page only follows when render() runs. Reload to get the original three books back.

Next, let people add books with the form. Listening for the form's submit event is covered properly in the event listeners tutorial linked at the end; here it is one handler that updates the array and calls render(). Append:

Bash
cd ~/dom-reading-list-demo
cat >> app.js <<'JS'

const form = document.querySelector('#add-book');
const lastAdded = document.querySelector('#last-added');

form.addEventListener('submit', (event) => {
  event.preventDefault();
  const data = new FormData(form);
  const title = data.get('title').trim();
  const author = data.get('author').trim();
  if (!title || !author) return;

  books.push({ id: Date.now(), title, author, status: 'to-read' });
  lastAdded.textContent = `Last added: ${title}`;
  form.reset();
  render();
});
JS

event.preventDefault() stops the browser from sending the form and loading a new page, so the script can handle it instead. For a list of a few dozen books, rebuilding every row on each change is quick. With thousands of rows you would update only the rows that changed, which is the work frameworks such as React and Vue do for you.

Check it worked

Reload. Type Purple Hibiscus <img src="x" onerror="alert(1)"> as the title and Chimamanda Ngozi Adichie as the author, then press Add book. A fourth row appears with the title exactly as typed, the "Last added" line shows the same text, the form clears, the address bar does not change, and no alert appears.

Step 8 · Test the page with Playwright

Clicking through by hand checks the page once. A test checks it every time you change the script. Install Playwright, which drives a real browser from a script, into the demo folder. --with-deps also installs the system libraries Chromium needs on Linux, which can ask for your password:

Bash
cd ~/dom-reading-list-demo
npm init -y > /dev/null
npm install playwright@1.65.1
npx playwright install --with-deps chromium

Then write a test that loads the page from your running server and checks each behaviour from this tutorial:

Bash
cd ~/dom-reading-list-demo
cat > test-reading-list.mjs <<'JS'
import { chromium } from 'playwright';
import assert from 'node:assert/strict';

const url = `http://127.0.0.1:${process.env.PORT ?? 8080}/`;
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 360, height: 740 } });
const dialogs = [];
const errors = [];
page.on('dialog', async (d) => { dialogs.push(d.message()); await d.dismiss(); });
page.on('pageerror', (e) => errors.push(e.message));
await page.goto(url);

const rows = page.locator('#books li');
const summary = page.locator('#summary');
const titles = () => page.locator('#books .title').allTextContents();

// Rows are drawn from the array through the template.
assert.equal(await rows.count(), 3);
assert.deepEqual(await titles(), ['Things Fall Apart', 'Weep Not, Child', 'Half of a Yellow Sun']);
assert.equal(await rows.nth(1).locator('.author').textContent(), "Ngũgĩ wa Thiong'o");
assert.equal(await summary.textContent(), '3 books, 1 read');
assert.equal(await rows.nth(0).getAttribute('data-status'), 'read');
assert.match(await rows.nth(0).getAttribute('class'), /\bis-read\b/);
assert.match(await rows.nth(1).getAttribute('class'), /\bis-current\b/);
assert.equal(await page.locator('#book-row').isVisible(), false, 'the template itself is not shown');

// Change the array, call render(), and the page follows.
await page.evaluate(() => {
  readingList.books[2].status = 'read';
  readingList.render();
});
assert.equal(await summary.textContent(), '3 books, 2 read');
assert.match(await rows.nth(2).getAttribute('class'), /\bis-read\b/);

// Typed HTML stays text and never runs.
const sneaky = 'Purple Hibiscus <img src="x" onerror="alert(1)">';
await page.getByLabel('Title').fill(sneaky);
await page.getByLabel('Author').fill('Chimamanda Ngozi Adichie');
await page.getByRole('button', { name: 'Add book' }).click();
assert.equal(await rows.count(), 4);
assert.equal(await rows.nth(3).locator('.title').textContent(), sneaky);
assert.equal(await page.locator('#last-added').textContent(), `Last added: ${sneaky}`);
assert.equal(await page.locator('main img').count(), 0, 'no img element was created');
assert.equal(await page.getByLabel('Title').inputValue(), '', 'the form was cleared');
assert.equal(page.url(), url, 'the form did not load a new page');

// Removing from the array removes the row.
await page.evaluate(() => {
  readingList.books.splice(0, 1);
  readingList.render();
});
assert.equal(await rows.count(), 3);
assert.equal((await titles())[0], 'Weep Not, Child');
assert.equal(await summary.textContent(), '3 books, 1 read');

await page.waitForTimeout(300);
assert.deepEqual(dialogs, [], 'no alert appeared');
assert.deepEqual(errors, [], 'no script errors');

await browser.close();
console.log('PASS: reading list renders from its array');
JS
node test-reading-list.mjs

The test uses a phone-sized window (360 by 740 pixels) and the same visible labels a person reads ("Title", "Add book"), so a renamed label breaks the test as it would confuse a user.

Check it worked

The last line of output is PASS: reading list renders from its array. To see it fail for the right reason, change textContent to innerHTML on the .title line in render() and run node test-reading-list.mjs again: it stops with an AssertionError and no PASS line. Change it back and the test passes.

Step 9 · Clean up

Stop the server with Ctrl+C in its terminal, then remove the demo folder, which also removes the local Playwright install. The browser Playwright downloaded stays in its shared cache; npx playwright uninstall removes that too if you no longer need it.

Bash
cd ~
rm -rf ~/dom-reading-list-demo

Check it worked

ls ~/dom-reading-list-demo reports that there is no such file or directory, and http://127.0.0.1:8080 no longer loads in your browser.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Digital Transformation

Get new tutorials

New tutorials, about twice a month.