Skip to content

The importance of timing when working with the DOM

New Course Coming Soon:

Get Really Good at Git

While working with the students in my bootcamp I helped a few of them navigate one problem: timing.

In particular, there’s one thing that might not be apparent at first.

When you access the value of a DOM element and you store it into a variable, that variable is NOT going to be updated with the new value when the DOM element changes.

Suppose you have an input field in a form <input id="temperature">, and you get its value in this way:

const temperature = document.querySelector('input#temperature').value

The temperature variable gets the value of the state of the input field at the moment the browser executes this statement, and then the value stays the same forever.

This is why you can’t do like this:

const temperature = document.querySelector('input#temperature').value

document.querySelector('form')
        .addEventListener('submit', event => {
  //send the temperature value to your server
})

but you need to access the temperature value when you submit the form:

document.querySelector('form')
        .addEventListener('submit', event => {
  const temperature = document.querySelector('input#temperature').value
  //send the temperature value to your server
})

Alternatively you can store the input field reference in a variable, and use that to access its value at submit:

const temperatureElement = document.querySelector('input#temperature')
document.querySelector('form')
        .addEventListener('submit', event => {
  const temperature = temperatureElement.value
  //send the temperature value to your server
})
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: