/

The Importance of Timing When Working with the DOM

The Importance of Timing When Working with the DOM

When working with the DOM, it is important to understand the concept of timing. One crucial detail that may not be immediately apparent is that when you access the value of a DOM element and store it into a variable, that variable will not be updated with the new value if the DOM element changes.

Let’s say you have an input field in a form <input id="temperature">, and you want to get its value. You might initially do this:

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

However, this temperature variable will only hold the value of the input field at the moment this statement is executed, and it will remain the same even if the input field’s value changes.

This means that you cannot do the following:

1
2
3
4
5
6
const temperature = document.querySelector('input#temperature').value;

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

Instead, you need to access the temperature value when you submit the form:

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

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

1
2
3
4
5
6
const temperatureElement = document.querySelector('input#temperature');
document.querySelector('form')
.addEventListener('submit', event => {
const temperature = temperatureElement.value;
// send the temperature value to your server
})

Tags: DOM manipulation, JavaScript, timing, variable update