Open In App
Related Articles

How getElementByID works in JavaScript ?

Improve Article
Save Article
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.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 10 Nov, 2021
Like Article
Save Article
Similar Reads
Complete Tutorials