CodeMIRAI
0 XP

Selecting elements

2 min read 3 runnable examples Quiz included

When a browser loads a web page, it turns the HTML into a tree of objects called the DOM (Document Object Model). JavaScript can read and change that tree, which is how pages become interactive.

documenthtmlheadbodytitleh1ul#listlilidocument.querySelector("#list") finds the ul node
The browser turns your HTML into a tree of objects. Selecting and changing nodes in the tree changes the page.

The whole page is available as document.

Selecting one element

document.querySelector() takes a CSS selector and returns the first matching element:

HTML
<h1 id="title">Welcome</h1>
<p class="intro">First paragraph</p>
<p class="intro">Second paragraph</p>

<script>
  const heading = document.querySelector("#title");    // by id
  const firstIntro = document.querySelector(".intro"); // by class
  console.log(heading.textContent);
  console.log(firstIntro.textContent);
</script>

document.getElementById("title") is an older, slightly faster way to select by id (no #).

Selecting several elements

querySelectorAll() returns all matches, which you can loop over:

HTML
<ul>
  <li>Python</li>
  <li>JavaScript</li>
  <li>SQL</li>
</ul>

<script>
  const items = document.querySelectorAll("li");
  console.log("Found", items.length, "items");
  items.forEach((li, i) => {
    li.textContent = `${i + 1}. ${li.textContent}`;
  });
</script>

The result appears in the page itself; check the rendered list above the console output.

Any CSS selector works

HTML
<div class="card"><h2>Card one</h2><p>Text <a href="#">link</a></p></div>
<div class="card featured"><h2>Card two</h2></div>

<script>
  console.log(document.querySelectorAll(".card").length);
  console.log(document.querySelector(".card.featured h2").textContent);
  console.log(document.querySelector(".card p a").textContent);
</script>
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.