The DOM and events
The document tree as seen from JavaScript: selecting, reading and modifying elements, listening to events, their propagation, preventDefault and delegation.
- 27 cards
- 3 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
A few cards from the deck
DOM: what is it?
Show the answer
The representation of the page as a tree of objects (elements, text, attributes) that JavaScript can read and modify, the displayed page following these changes.
The DOM is not the HTML file: it is the tree the browser builds from it. A script that alters it does not change the file on the server.
How many elements does the list returned by
document.querySelectorAll('ul li.done')hold?
```html
<ul>
<li>Lait</li>
<li class="done">Pain</li>
<li class="done">Riz</li>
</ul>
<ol>
<li class="done">Thé</li>
</ol>`2314
Show the answer
2The selector
ul li.doneasks forlielements with classdoneinside aul: Pain and Riz. Thé is in anol, Lait lacks the class.In a listener, the event object gives the element actually targeted by the … property and the one carrying the listener by the … property.
Show the answer
In a listener, the event object gives the element actually targeted by the target property and the one carrying the listener by the currentTarget property.
With delegation on a
ul,currentTargetis always theul, whereastargetis thelior button clicked.querySelector: what is it?
Show the answer
A method that takes a CSS selector and returns the first matching element, or null if there is none.
querySelectorAllreturns all matching elements in a list (empty if there are none). Using thenullresult causesCannot read properties of null.This script is placed in the
head, withoutdefer. What happens?
```javascript
const bouton = document.querySelector('#envoyer');
bouton.addEventListener('click', envoyer);`- Nothing: the script waits quietly until the button appears, then sets the listener
TypeError: Cannot read properties of null (reading 'addEventListener')SyntaxError: Unexpected identifier 'bouton', raised as the file is loaded- The button exists, but the listener ends up being called twice per click
Show the answer
TypeError: Cannot read properties of null (reading 'addEventListener')The browser runs the script before it has built the
body: the selector finds nothing and returnsnull. Fix:<script defer src="…">, which waits until the document is parsed.