Multiple elements and event delegation

INPUT · Slides

Grab many at once with querySelectorAll

01 / 03

One at a time or all of them

So far you have used getElementById to grab exactly one element by its id. That works when you know the id.

But what if you want every row in the list? Rows are added on the fly — you cannot put an id on all of them.

02 / 03

querySelectorAll uses CSS selectors

document.querySelectorAll("#list li") returns every li inside #list — all of them at once.

It takes the same selectors you write in CSS. .done finds elements with the done class. #list li.is-done finds only the finished rows.

const items = document.querySelectorAll("#list li")console.log(items.length) // number of rows

03 / 03

length for the count, for...of to loop

What comes back is array-like (a NodeList). Use .length for the count and for...of to walk through them.

querySelector (no All) returns just the first match. Use that when one is enough.

for (const item of items) {  console.log(item.textContent)}