JavaScript – getElementById()

JavaScript getElementById() – In this tutorial, we shall learn to access an HTML DOM element by its unique id.

To access an HTML DOM element with the help of its id value, use document.getElementById(<id_value>) method.

Syntax

The syntax of getElementById() function is

document.getElementById(id_value)

In html,

<htmlTag id="id_value">

</htmlTag>

htmlTag could be any html tag. For example : html, body, div, h1, h2, h3, p, img, a, etc.

Note: Please observe the casing in the function name, getElementById. During the initial stages, beginners might type it incorrectly.

As id is maintained uniquely for HTML DOM elements, document.getElementById() function returns object of only one element whose id matches.

If it doesn’t find an HTML DOM element with the specified id, nothing is returned.

ADVERTISEMENT

Example

In the following example, we shall access an HTML DOM element, a paragraph with id=”message” and modify its content.

index.html

Conclusion

In this JavaScript Tutorial, we have learnt how to access an HTML DOM element using its id, and change its innerhtml text.