querySelector
Finding elements.
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.

- 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.
<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>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.
| key | value |
|---|---|
| #id | one element by id |
| .class | by class |
| querySelector | first match |
| querySelectorAll | every 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