JavaScript getElementById method

The getElementById is a method of document object (DOM). The getElementById takes a parameter, Id of the element (as the name shows “get Element By Id”).

An example of getElementById

See the syntax below for using it.

How to use the JavaScript getElementById

Following is the general syntax to use the getElementById method:

document.getElementById(element_id);

A few points about getElementById function

  • As mentioned earlier, the getElementByid is DOM function so you have to use the document.getElementById in order to use it.
  • getElementById takes one parameter which is an element id in HTML document.
  • Examples of using the getElementById can be getting values of input fields or setting the style of HTML elements.
  • If more than one HTML elements are using the same ID then getElementById will return the first element.
  • If no element id exists then it will return null.
  • In getElementById, I is capital i.e. (get Element By Id).

Following are a few examples of using getElementById method

A getElementByid value example

Following is a JavaScript document.getElementByid example to get the value of the element. We are using a textbox with id=txtex and then use the getElementByid to show the value of text entered in the textbox. Click the link or image below to see the online demo.

Experience this example online

As you can see, the textbox value is shown by using the JavaScript getElementById in an alert.

getElementById example to set textbox value

Not only you can get value by using the getElementById method but also you can set the value as shown in the example below. Click on the button and the text will be set to textbox by using getElementById.

Experience this example online

The getElementById example to change the background color

Following example shows how to change the background color by using the getElementById method. We have created a div element with white background (default).

As you click on the button, the JavaScript function will execute that will change the background color of div by using getElementById.

Experience this example online

As you can see the background color will be changed to green as you click on the button by using the getElementById function.