Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How getElementByID works in JavaScript ?

  • Last Updated : 10 Nov, 2021

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.

Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.

Syntax:

const gfg = document.getElementById(id);

Parameters:



  • 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.

HTML




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


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.

getElementByID

My Personal Notes arrow_drop_up
Recommended Articles
Page :