Sometimes, we want to get element by ID and set the value with JavaScript.
In this article, we’ll look at how to get element by ID and set the value with JavaScript.
How to get element by ID and set the value with JavaScript?
To get element by ID and set the value with JavaScript, we make sure the element is loaded before we try to set its value.
For instance, we write
<input id="id" type="text" value="" />
to add an input.
Then we write
const setValue = (id, newValue) => {
const s = document.getElementById(id);
s.value = newValue;
};
window.onload = () => {
setValue("id", "Hello there");
};
to call setValue
in the window.onload
method to make sure the input is loaded before we set the value.
In setValue
, we get the element with getElementById
.
Then we set its value
to newValue
.
Conclusion
To get element by ID and set the value with JavaScript, we make sure the element is loaded before we try to set its value.