JavaScript DOM: Select, Read and Change Page Elements

Every web page you test is a tree of objects called the DOM. JavaScript in the browser reads and changes that tree: it finds elements, reads their text, changes classes and adds new rows. This is how web apps update without reloading, and it is exactly what automation tools such as Playwright and Selenium do under the hood when they locate an element. In this lesson you will select elements with CSS selectors, move around the tree, read and change text, attributes, classes and styles, and create and remove elements. Every example below was run in real Chrome: you see the index.html, the app.js it loads, and what appeared in the browser console.

Advertisement

📖 What You’ll Learn: what the DOM is, how to run DOM code in the browser, getElementById, querySelector and querySelectorAll, NodeList vs HTMLCollection, traversing with parentElement, children, closest and siblings, textContent vs innerText vs innerHTML, attributes vs properties, data attributes, classList and inline styles, getComputedStyle, creating, inserting, cloning and removing elements, and extracting page data like a tester.


🌳 What Is the DOM?

Definition: the DOM (Document Object Model) is the browser’s live, in-memory representation of a page: a tree of nodes built from the HTML. Each tag becomes an element object with properties and methods, and the global document object is the entry point to the tree.

🌳 The DOM tree of the example page

document
└── html
    ├── head
    │   └── title  "Demo"
    └── body
        ├── h1#title          "Product List"
        ├── ul#products
        │   ├── li.product    "USB Cable"
        │   ├── li.product.sale "Headphones"
        │   └── li.product    "Mouse"
        └── p.note            "Prices in INR"
  • The HTML file is the source; the DOM is what the browser builds from it, and JavaScript can change the DOM at any time.
  • DevTools → Elements shows the current DOM, not the original HTML, which is why it can differ from “View Page Source”.
  • The DOM exists only in browsers. Node.js has no document (tools such as jsdom imitate it).

💡 Tip: To try these examples, save index.html and app.js in one folder and open index.html with the VS Code Live Server extension (it serves the page at http://localhost:5500), then open DevTools with F12 → Console. You can also paste the app.js code straight into the Console of any page.


🎯 Selecting Elements

querySelector takes any CSS selector and returns the first match, or null. querySelectorAll returns all matches as a NodeList:

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>
  <h1 id="title">Product List</h1>
  <ul id="products">
    <li class="product" data-id="101" data-price="499">USB Cable</li>
    <li class="product sale" data-id="102" data-price="1299">Headphones</li>
    <li class="product" data-id="103" data-price="799">Mouse</li>
  </ul>
  <p class="note">Prices in INR</p>
  <script src="app.js"></script>
</body>
</html>

📄 app.js

const title = document.getElementById("title");        // by id (no #)
const firstProduct = document.querySelector(".product"); // first match
const allProducts = document.querySelectorAll(".product");
const onSale = document.querySelector("li.sale");
const mouse = document.querySelector('[data-id="103"]');   // attribute selector
const missing = document.querySelector(".does-not-exist");

console.log(title.textContent);
console.log(firstProduct.textContent);
console.log(allProducts.length, "products");
console.log(onSale.textContent, "|", mouse.textContent);
console.log("missing:", missing);

🖥️ Browser console

Product List
USB Cable
3 products
Headphones | Mouse
missing: null
MethodReturnsNote
getElementById("id")Element or nullFastest; no #
querySelector(css)First element or nullAny CSS selector
querySelectorAll(css)Static NodeListHas forEach; does not update
getElementsByClassName(name)Live HTMLCollectionUpdates automatically; no forEach
getElementsByTagName(tag)Live HTMLCollectionOlder style

Any element also has querySelector, so you can search inside it, the same idea as chaining locators in Playwright. A NodeList is not an array; spread it ([...list]) or use Array.from to get map and filter:

📄 app.js

const list = document.querySelector("#products");
const items = list.querySelectorAll("li");              // search inside the list only

items.forEach((li) => console.log(li.dataset.id, li.textContent));

const names = [...items].map((li) => li.textContent);
const expensive = Array.from(items).filter((li) => Number(li.dataset.price) > 700);
console.log(names);
console.log(expensive.map((li) => li.textContent));

🖥️ Browser console

101 USB Cable
102 Headphones
103 Mouse
["USB Cable","Headphones","Mouse"]
["Headphones","Mouse"]

⚠️ Watch out: Calling a method on a selector that matched nothing is the most common DOM error: document.querySelector(".typo").textContent throws TypeError: Cannot read properties of null. Check for null, or use optional chaining: el?.textContent.


🧭 Moving Around the Tree

From any element you can walk to its relatives. The ...Element... properties skip text and whitespace nodes, so prefer them:

📄 app.js

const headphones = document.querySelector(".sale");

console.log(headphones.parentElement.id);                 // the <ul>
console.log(headphones.previousElementSibling.textContent);
console.log(headphones.nextElementSibling.textContent);
console.log(headphones.parentElement.children.length);
console.log(headphones.closest("ul").id);                // nearest ancestor matching a selector
console.log(headphones.closest(".missing"));             // none -> null
console.log(headphones.matches("li.product.sale"));      // does it match a selector?

🖥️ Browser console

products
USB Cable
Mouse
3
products
null
true
Property / methodGives
parentElementThe parent element
childrenChild elements (HTMLCollection)
firstElementChild / lastElementChildFirst / last child element
previousElementSibling / nextElementSiblingNeighbours
closest(css)Itself or the nearest ancestor that matches
matches(css)true if the element matches the selector

💡 Tip: closest() is the tester’s friend: from a “Delete” button, button.closest("tr") finds its table row, the same as filtering rows by their content in Playwright.


Advertisement

✏️ Reading and Changing Content

There are three ways to get the content of an element, and the difference matters:

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>
  <p id="msg">Order <strong>#4521</strong> placed.<span style="display:none"> (internal id 99)</span></p>
  <script src="app.js"></script>
</body>
</html>

📄 app.js

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

console.log("textContent:", msg.textContent);   // all text, including hidden text
console.log("innerText:  ", msg.innerText);     // only text a user can see
console.log("innerHTML:  ", msg.innerHTML);     // the HTML markup inside

msg.textContent = "Order <b>#4522</b> placed.";   // set as plain text: tags are NOT parsed
console.log(msg.innerHTML);

msg.innerHTML = "Order <b>#4522</b> placed.";     // set as HTML: tags ARE parsed
console.log(msg.querySelector("b").textContent);

🖥️ Browser console

textContent: Order #4521 placed. (internal id 99)
innerText:   Order #4521 placed.
innerHTML:   Order <strong>#4521</strong> placed.<span style="display:none"> (internal id 99)</span>
Order &lt;b&gt;#4522&lt;/b&gt; placed.
#4522
PropertyReadsUse for
textContentAll text of the element and its descendants, hidden or notReading and setting plain text (fast and safe)
innerTextOnly rendered, visible text (respects CSS)What the user actually sees
innerHTMLThe HTML markupInserting trusted HTML

⚠️ Watch out: Never put user input or API data into innerHTML. Text like <img src=x onerror=alert(1)> becomes real HTML and runs script, which is a cross-site scripting (XSS) hole. Use textContent for data. Testers often try such strings in input fields precisely to find this bug.


🏷️ Attributes, Properties and data-*

HTML attributes are what is written in the markup; DOM properties are the live values on the element object. For form fields they can differ: the value attribute is the initial value, the value property is what is in the box now.

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>
  <a id="help" href="/help" target="_blank">Help</a>
  <input id="qty" type="number" value="1">
  <button id="buy" data-product-id="102" data-in-stock="true">Buy</button>
  <script src="app.js"></script>
</body>
</html>

📄 app.js

const link = document.querySelector("#help");
console.log(link.getAttribute("href"));   // exactly what the HTML says
console.log(link.href);                   // property: the full resolved URL
link.setAttribute("target", "_self");
console.log(link.hasAttribute("target"), link.getAttribute("target"));

const qty = document.querySelector("#qty");
qty.value = "3";                          // what a user typing would change
console.log("property:", qty.value, "| attribute:", qty.getAttribute("value"));

const buy = document.querySelector("#buy");
console.log(buy.dataset.productId, buy.dataset.inStock);   // data-product-id -> productId
buy.dataset.inStock = "false";
buy.disabled = true;                       // boolean property adds the attribute
console.log(buy.outerHTML);

🖥️ Browser console

/help
http://localhost:5500/help
true _self
property: 3 | attribute: 1
102 true
<button id="buy" data-product-id="102" data-in-stock="false" disabled="">Buy</button>

Notice that data-product-id becomes dataset.productId (dashes to camelCase), and every dataset value is a string. Test-id attributes such as data-testid exist so tests can find elements by a stable hook, which is what Playwright’s getByTestId() reads.


🎨 Classes and Styles

Change appearance by toggling CSS classes with classList, and only set inline style for one-off values. getComputedStyle reads the final style after all CSS rules, which is how you check whether something is really hidden:

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
  <style>
    .hidden { display: none; }
    .error { color: rgb(220, 38, 38); }
  </style>
</head>
<body>
  <p id="alert" class="message hidden">Payment failed</p>
  <script src="app.js"></script>
</body>
</html>

📄 app.js

const alertBox = document.querySelector("#alert");

console.log([...alertBox.classList]);
alertBox.classList.remove("hidden");
alertBox.classList.add("error");
alertBox.classList.toggle("bold");          // adds it if missing, removes it if present
console.log(alertBox.className);
console.log(alertBox.classList.contains("error"));

alertBox.style.fontSize = "18px";           // inline style: camelCase property names
const style = getComputedStyle(alertBox);
console.log(style.color, style.display, style.fontSize);

🖥️ Browser console

["message","hidden"]
message error bold
true
rgb(220, 38, 38) block 18px
MethodDoes
classList.add("a", "b")Add one or more classes
classList.remove("a")Remove a class
classList.toggle("a", force?)Add or remove; force true/false sets it explicitly
classList.contains("a")Check a class
classList.replace("a", "b")Swap one class for another

Advertisement

➕ Creating, Inserting and Removing Elements

document.createElement makes a new element that is not on the page yet; append, prepend, before and after put it in place:

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>
  <ul id="todo">
    <li>Write test plan</li>
  </ul>
  <script src="app.js"></script>
</body>
</html>

📄 app.js

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

const item = document.createElement("li");
item.textContent = "Run smoke tests";
item.className = "new";
list.append(item);                                  // add as last child

const urgent = document.createElement("li");
urgent.textContent = "Fix login bug";
list.prepend(urgent);                               // add as first child

list.insertAdjacentHTML("beforeend", "<li>Report results</li>");

const copy = item.cloneNode(true);                  // deep copy with children
copy.textContent = "Run regression tests";
item.after(copy);

console.log([...list.children].map((li) => li.textContent));

list.firstElementChild.remove();                    // delete an element
console.log(list.children.length, "items left");
console.log(list.outerHTML);

🖥️ Browser console

["Fix login bug","Write test plan","Run smoke tests","Run regression tests","Report results"]
4 items left
<ul id="todo">
    <li>Write test plan</li>
  <li class="new">Run smoke tests</li><li class="new">Run regression tests</li><li>Report results</li></ul>

Adding many elements one at a time makes the browser recalculate the layout repeatedly. Build them in a DocumentFragment (or an array passed to append(...items)) and insert once:

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>
  <table id="results"><tbody></tbody></table>
  <script src="app.js"></script>
</body>
</html>

📄 app.js

const results = [
  { test: "login", status: "passed" },
  { test: "cart", status: "failed" },
  { test: "logout", status: "passed" },
];

const fragment = document.createDocumentFragment();
for (const r of results) {
  const row = document.createElement("tr");
  const name = document.createElement("td");
  name.textContent = r.test;
  const status = document.createElement("td");
  status.textContent = r.status;
  status.className = r.status;
  row.append(name, status);
  fragment.append(row);
}
document.querySelector("#results tbody").append(fragment);   // one insertion

console.log(document.querySelectorAll("#results tr").length, "rows");
console.log(document.querySelectorAll("td.failed").length, "failed");

🖥️ Browser console

3 rows
1 failed

🧪 Tester Scenario: Extract and Verify Table Data

Testers often need to check that a page shows correct data: totals that add up, sorted columns, no duplicates. Reading the DOM into plain objects makes those checks easy, and it is exactly what page.$$eval or locator.evaluateAll do in Playwright:

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>
  <table id="cart">
    <thead><tr><th>Item</th><th>Qty</th><th>Price</th></tr></thead>
    <tbody>
      <tr><td>USB Cable</td><td>2</td><td>₹499</td></tr>
      <tr><td>Mouse</td><td>1</td><td>₹799</td></tr>
      <tr><td>Keyboard</td><td>1</td><td>₹1,499</td></tr>
    </tbody>
  </table>
  <p>Total: <span id="total">₹3,197</span></p>
  <script src="app.js"></script>
</body>
</html>

📄 app.js

const toNumber = (text) => Number(text.replace(/[^\d.]/g, ""));   // "₹1,499" -> 1499

const headers = [...document.querySelectorAll("#cart thead th")].map((th) => th.textContent.toLowerCase());
const rows = [...document.querySelectorAll("#cart tbody tr")].map((tr) => {
  const cells = [...tr.cells].map((td) => td.textContent.trim());
  return Object.fromEntries(headers.map((h, i) => [h, cells[i]]));
});
console.log(rows);

const expected = rows.reduce((sum, r) => sum + toNumber(r.qty) * toNumber(r.price), 0);
const shown = toNumber(document.querySelector("#total").textContent);
console.log(`expected ${expected}, shown ${shown}`);
console.log(expected === shown ? "✓ total is correct" : "✗ total is WRONG");

🖥️ Browser console

[{"item":"USB Cable","qty":"2","price":"₹499"},{"item":"Mouse","qty":"1","price":"₹799"},{"item":"Keyboard","qty":"1","price":"₹1,499"}]
expected 3296, shown 3197
✗ total is WRONG

The page shows ₹3,197, but 2 × 499 + 799 + 1,499 = 3,296: a real calculation bug, found in a few lines of JavaScript.


Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Select the element with id price and print its text, then change it to “₹999”.

Show answer

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>
  <span id="price">₹1,299</span>
  <script src="app.js"></script>
</body>
</html>

📄 app.js

const price = document.getElementById("price");
console.log(price.textContent);
price.textContent = "₹999";
console.log(price.textContent);

🖥️ Browser console

₹1,299
₹999

Q2. Print the text of every li inside #menu as an array.

Show answer

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>
  <ul id="menu"><li>Home</li><li>Courses</li><li>Practice</li></ul>
  <script src="app.js"></script>
</body>
</html>

📄 app.js

const names = [...document.querySelectorAll("#menu li")].map((li) => li.textContent);
console.log(names);

🖥️ Browser console

["Home","Courses","Practice"]

Q3. Add the class active to the second tab and remove it from the first.

Show answer

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>
  <div class="tab active">Login</div>
  <div class="tab">Register</div>
  <script src="app.js"></script>
</body>
</html>

📄 app.js

const tabs = document.querySelectorAll(".tab");
tabs[0].classList.remove("active");
tabs[1].classList.add("active");
console.log([...tabs].map((t) => t.className));

🖥️ Browser console

["tab","tab active"]

Q4. Create a <p> with the text “Saved successfully” and the class toast, and add it to the end of body.

Show answer

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>
  <main>App</main>
  <script src="app.js"></script>
</body>
</html>

📄 app.js

const toast = document.createElement("p");
toast.textContent = "Saved successfully";
toast.classList.add("toast");
document.body.append(toast);
console.log(document.querySelector(".toast").outerHTML);

🖥️ Browser console

<p class="toast">Saved successfully</p>

Q5. Read the data-status of every row and count how many are “failed”.

Show answer

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>
  <div class="row" data-status="passed">login</div>
  <div class="row" data-status="failed">cart</div>
  <div class="row" data-status="failed">search</div>
  <script src="app.js"></script>
</body>
</html>

📄 app.js

const failed = [...document.querySelectorAll(".row")].filter((r) => r.dataset.status === "failed");
console.log(failed.length, failed.map((r) => r.textContent));

🖥️ Browser console

2 ["cart","search"]

Q6. This line throws TypeError: Cannot read properties of null. Why, and how do you make it safe?

document.querySelector("#sumbit").textContent
Show answer

The selector has a typo (#sumbit), so querySelector returns null. Check the result first or use optional chaining:

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>
  <button id="submit">Submit</button>
  <script src="app.js"></script>
</body>
</html>

📄 app.js

const button = document.querySelector("#sumbit");
console.log(button?.textContent ?? "button not found - check the selector");
console.log(document.querySelector("#submit")?.textContent);

🖥️ Browser console

button not found - check the selector
Submit

🧠 MCQ Quiz: DOM Manipulation

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What is the DOM?
  2. What does document.querySelector(".item") return when nothing matches?
  3. Which method returns ALL matching elements?
  4. Which property returns only the text a user can see?
  5. Why is setting innerHTML from user input dangerous?
  6. How do you read data-user-id="7"?
  7. Which call adds a CSS class?
  8. What does el.closest("tr") return?
  9. After a user types 5 into <input value="1">, what is input.getAttribute("value")?
  10. Which is the efficient way to add 500 rows?

💼 Interview Questions and Answers

Q1. What is the difference between textContent, innerText and innerHTML?

textContent returns all text nodes, including text hidden by CSS, and is fast because it ignores layout. innerText returns only rendered, visible text, so it triggers layout and respects display: none. innerHTML returns or sets the HTML markup. For assertions on what users see, innerText (or Playwright’s toHaveText, which normalises whitespace) is closer to reality; for setting data, use textContent to avoid XSS.

Q2. NodeList vs HTMLCollection?

querySelectorAll returns a static NodeList: a snapshot that does not change when the DOM changes, and it has forEach. getElementsByClassName and children return a live HTMLCollection that updates automatically, without forEach. Neither is an array; convert with [...list] or Array.from.

Q3. How do automation tools find elements, and why are some locators more stable than others?

They query the DOM, like querySelector, using CSS, XPath, text, roles or test ids. Locators tied to page structure (div > div:nth-child(3)) or generated class names break when the layout changes. Locators based on what users see or on dedicated hooks (role and accessible name, label text, data-testid) stay stable across refactors, which is why Playwright recommends getByRole and getByTestId.

Q4. Attribute vs property: give an example where they differ.

For an input, the value attribute is the initial value from the HTML, while the value property is the current content. After a user types, input.value changes but getAttribute("value") does not. Similarly, getAttribute("href") returns the relative path as written, and the href property returns the full resolved URL. Use properties for current state.


Advertisement

❓ Frequently Asked Questions

🤔 Can I use the DOM in Node.js?

Not natively; document does not exist there. Test runners such as Jest and Vitest can use jsdom or happy-dom to imitate it, and Playwright drives a real browser instead.

🤔 Is getElementById faster than querySelector?

Slightly, but the difference is negligible for almost all code. Use whichever is clearer; querySelector is more flexible because it accepts any CSS selector.

🤔 Why does my script say the element is null although it is in the HTML?

The script ran before the element was parsed. Put the <script> at the end of body, add the defer attribute, or wait for the DOMContentLoaded event.

🤔 What is the shadow DOM?

A hidden, encapsulated DOM tree inside some components (web components). document.querySelector does not see inside it; you go through element.shadowRoot. Playwright locators pierce open shadow roots automatically.


🏁 Summary

  • The DOM is the browser’s live tree of the page; document is the entry point.
  • Select with querySelector / querySelectorAll (CSS selectors) and check for null.
  • Move around with parentElement, children, siblings and closest().
  • Read and set text with textContent; use innerHTML only for trusted HTML; use dataset, attributes and classList for state and styling.
  • Create with createElement, insert with append/before/after, remove with remove(), and read page data into objects to verify it.

Next, continue with Lesson 58: Events and Delegation.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in