Categories
JavaScript Answers

How to Get an Element by ID and Set the Value with JavaScript?

Spread the love

To get an element by ID and set the value with JavaScript, we can call document.getElementById with the ID string to get the element by its ID.

Then we can set the innerText property of the retrieved element if it’s not an input element.

Otherwise, we can set the value property of it.

For instance, if we have the following HTML:

<div id="theValue1"></div>  
<input id="theValue2">

Then we can set the innerText of the div by writing:

document.getElementById("theValue1").innerText = "value div";

And we can set the value of the input by writing:

document.getElementById("theValue2").value = "value input";

We call document.getElementById with the value of the id attribute of each element as a string.

Then we set the innerText property value of the div to put some text inside it.

And we set the value property of the input to set the text inside the input box.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.