The importance of timing when using the DOM

While working with students in my training camp, I helped some people solve a problem: timing.

In particular, one thing may not be obvious at first.

When you access the value of a DOM element and store it in a variable, the variable isIs notWhen the DOM element changes, it will be updated with the new value.

Suppose you have an input field in the form<input id="temperature">, You can get its value in the following ways:

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

ThistemperatureThe variable gets the state value of the input field when the browser executes this statement, and then the value remains unchanged forever.

This is why you cannot do this:

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

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

But when submitting the form, you need to access the temperature value:

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

Or you can store the input fieldreferenceIn a variable, and use it 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
})

Download mine for freeJavaScript beginner's manual


More js tutorials: