CHAPTER 3 · 3 lessons · 3 exercises
Multiple elements and event delegation
Grab elements in bulk and handle them with one listener on the parent.
Until now you have been grabbing elements one at a time with getElementById and attaching one listener each. Fine for five rows. What about fifty? A hundred?
This chapter hands you two new tools.
The first is querySelectorAll. Write a CSS selector and it returns every element that matches — all at once. getElementById is the shortcut for one known id; querySelectorAll finds as many as you like by condition. This chapter distinguishes finding one known id from finding several elements by a condition.
The second is event delegation. No matter how many rows there are, the listener sits on the parent, just one. When something is pressed, the event bubbles up from child to parent. Catch it there, check event.target, and you know what was pressed. Use closest and you know which row it belongs to.
Finally, you combine the two into a batch operation: clear every finished row in one go. Select with a filter, loop, do something to all of them — the most general DOM pattern there is.
Lessons in this chapter
Grab many at once
- 09Grab many at once with querySelectorAllgetElementById finds one. querySelectorAll finds every element that matches — all in one go.Go to the exercises
Delegate
- 10One listener for every rowInstead of a listener per row, put one on the parent and use event.target to sort it out.Go to the exercises
Operate in bulk
- 11Clear finished items in one goUse querySelectorAll to find every marked row, then loop and remove them all.Go to the exercises