AI Hints
Home›JavaScript Tutorial›JavaScript in the Browser
JavaScript · Lesson 93 of 138

querySelector

Finding elements.

⏱ 2 min read▶ Video at 1:51:56🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Walking the tree by position is fragile. Add one element, and the numbers change. Instead, find elements the way CSS does, with selectors. Query selector takes any CSS selector, and returns the first match.

querySelector
From the video: querySelector
  • Positions are fragile
  • Use CSS selectors
  • querySelector

Selectors

Query selector with a hash finds by i d. With a dot, by class. Query selector all returns every match, and we can loop over them with for each. Here, the title gets a new text, and every item with the class sale gets a box style.

index.htmlpython
<link rel="stylesheet" href="style.css">
<h1 id="title">Menu</h1>
<ul>
  <li class="sale">Soup</li>
  <li>Salad</li>
  <li class="sale">Pasta</li>
</ul>
<script>
  document.querySelector("#title").textContent = "Today's Menu";

  const deals = document.querySelectorAll(".sale");
  deals.forEach(li => li.classList.add("box"));
  console.log(deals.length);
</script>
Output
2
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#f7df1e;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}

Ways to select

Use an i d for one special element, and classes for groups. Query selector returns null if nothing matches, so check before using it. You can use any CSS selector, like ul space li, or input with type equals email.

keyvalue
#idone element by id
.classby class
querySelectorfirst match
querySelectorAllevery match

Summary

Query selector finds the first element matching a CSS selector, and query selector all finds them all. Next, changing text, classes, and styles.

Key takeaways
  • querySelector('#id')
  • querySelectorAll('.cls')
  • null if missing
Next up: Changing the Page — text, classes, styles