Skip to content
Related Articles

Related Articles

Improve Article

How getElementByID works in JavaScript ?

  • Last Updated : 17 Mar, 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.

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. Below example illustrates the use of getElementById.

Example:



HTML




<!DOCTYPE html>
<html lang="en">
  
<body>
  <!-- defing 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.

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :