← The DOM and the browser console

DOM and JavaScript reference

Finding and changing elements, events, and loading data with fetch.

Print a cheat sheet (the whole course or one unit, with a picture of what each command draws)

JavaScript (recipes)

document.querySelector('#go').addEventListener('click', function () {
  what to do
});
on click

When the element with id="go" is clicked, run the lines inside. # means id, as . means class.

id: on-click

document.querySelector('#message').textContent = 'Go!';
change the text

Replace the words inside the element with id="message".

id: change-the-text

const name = document.querySelector('#name').value;
read a box

Read what someone typed into the box with id="name".

id: read-a-box

Fetch and JSON

const response = await fetch("weather.json");
const data = await response.json();

Example

<p id="out">Loading…</p>
<script>
  async function load() {
    const response = await fetch("weather.json");
    const data = await response.json();
    document.querySelector("#out").textContent = "Days: " + data.daily.time.length;
  }
  load();
</script>
fetch JSON

Asks for a file or web address, waits for the reply, then turns it into data (objects and arrays). Both lines need await, inside an async function.

What the example draws
Loading… becomes Days: 7 once the file has arrived

id: fetch-json

async function load() {
  … await …
}
load();
async function

A function that may wait for slow things with await. Call it like any function; the rest of the page keeps going while it waits.

id: async-function

try {
  what might fail
} catch (error) {
  plan B
}
try and catch

Runs the lines in try; if one fails (no network, a blocked site), jumps to catch instead of stopping with an error.

id: try-and-catch