Open In App

How getElementByID works in JavaScript ?

Last Updated : 10 Nov, 2021
Like Article

The document method getElementById() returns an element object representing the element whose id property matches with the given value. This method is used to manipulate an element on our document & is widely used in web designing to change the value of any particular element or get a particular element. If the passed ID to the method does not exist then it returns null.

A unique id should be used in the web pages. Although, if there is more than one element for the specific id exist then the only first element will consider & return by getElementByID in the code.


const gfg = document.getElementById(id);


  • id: The id of the element which we want to grab. The is a case-sensitive string that is unique within the document.

Return value: An element object with the specified id, or null if no matching element is found. 

Example: The below example illustrates the use of getElementById, by getting the element having the id attribute for the specified value.


<!DOCTYPE html>
<html lang="en">
    <!-- defining an element with an id -->
    <h1 id="gfg">GeeksforGeeks</h1>
    <!-- Adding javascript -->
    // Grabbing element
    const gfg = document.getElementById('gfg');

Output: Here, you can see “GeeksforGeeks” printed in the console tab. Now, after grabbing an element, we can perform any operations on that element like changing text, adding style, etc.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads