Categories
JavaScript Answers

How to get element by ID and set the value with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *