JavaScript getElementById() Method Tutorial

In this section, we will learn what the document getElementById() method is and how to use it in JavaScript.

What is document getElementById() Method in JavaScript?

The document getElementById() method is a way of getting a reference to an element in an HTML document in JavaScript by using the value that is assigned to the id attribute.

For example, let’s say you have an HTML document with three paragraphs (<p> elements). The first element has the id value of “p1”, the second one has the id value of “p2” and the third one has the value of “p3”. Now in JavaScript, if we want to get a reference to the first paragraph with the help of its id value, all we need to do is to use the value of this attribute and put it as the argument of the getElementById() method. After that, a reference of that element will return, which we can use to modify the target element.

document getElementById() Method Syntax:

document.getElementById(id);

document getElementById() Method Parameters

The method takes one parameter, and that is the value of an id attribute.

document getElementById() Method Return Value

The return value of the getElementById() method is an object reference to the target element in an HTML document.

Note: because the value for an id attribute is set to be unique, calling this method only returns one reference to an element that has this value for its id. That means if in a page, mistakenly there are multiple elements with the same value for their id attribute, only a reference to one of them will return and not a collection of references!

Example: using document getElementById() Value in JavaScript

See the Pen using document getElementById() Value in JavaScript by Omid Dehghan (@odchan1) on CodePen.

How does JavaScript getElementById() method work?

Here we’ve used this method to access the body element in this document by setting the value “body” which is the current value of its id attribute as the argument of this method. After that, we’ve used the `style` property of the returned object and the backgroundColor property to change the background color of the <body> element to light-blue.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies