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 | const temperature = document.querySelector('input#temperature').value; |
Instead, you need to access the temperature value when you submit the form:
1 | document.querySelector('form') |
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 | const temperatureElement = document.querySelector('input#temperature'); |
Tags: DOM manipulation, JavaScript, timing, variable update