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>)
Try Online

In html,

<htmlTag id="id_value">

</htmlTag>
Try Online

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.

Example – JavaScript getElementById()

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

<!doctype html>
<html>
<body>
	<h1>JavaScript getElementById() Example</h1>
	<p id="message"></p>
	<script>
      var messageElement = document.getElementById("message");
      messageElement.innerHTML = "This is how we access an HTML DOM element using its id value.";
	</script>
	
</body>
</html>
Try Online

Try Online

Conclusion

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