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.

  1. Concepts
  2. Questions
  3. 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>
    `

    • 2
    • 3
    • 1
    • 4
    Show the answer

    2

    The selector ul li.done asks for li elements with class done inside a ul: Pain and Riz. Thé is in an ol, 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, currentTarget is always the ul, whereas target is the li or 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.

    querySelectorAll returns all matching elements in a list (empty if there are none). Using the null result causes Cannot read properties of null.

  • This script is placed in the head, without defer. 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 returns null. Fix: <script defer src="…">, which waits until the document is parsed.