Skip to content
Related Articles

Related Articles

HTML | DOM getElementById() Method
  • Last Updated : 25 Jul, 2019

The getElementById() method returns the elements that has given ID which is passed to the function. This function is widely used in web designing to change the value of any particular element or get a particular element. If passed ID to the function does not exits then it returns null.

Syntax:

document.getElementById( element_ID )

Parameter: This function accepts single parameter element_ID which is used to hold the ID of element.

Return Value: It returns the object of given ID. If no element exists with given ID then it returns null.

Example 1:






<!DOCTYPE html> 
<html
    <head
        <title>
            DOM getElementById() Method
        </title
          
        <script
          
        // Function to change the color of element
        function geeks() {
            var demo = document.getElementById("geeks");
            demo.style.color = "green";
        
        </script
    </head
      
    <body style = "text-align:center">
      
        <h1 id = "geeks">GeeksforGeeks</h1>
          
        <h2>DOM getElementById() Method</h2>
          
        <!-- Click on the button to change color -->
        <input type = "button" onclick = "geeks()"
            value = "Click here to change color" />
    </body
</html>                    

Output:
Before click on the button:

After click on the button:

Example 2:




<!DOCTYPE html> 
<html
    <head
        <title>
            DOM getElementById() Method
        </title
          
        <script>
          
            // Function to change content of element
            function geeks() {
                var demo = document.getElementById("geeks");
                demo.innerHTML = "Welcome to GeeksforGeeks!" ;
            
        </script
    </head
      
    <body style = "text-align:center">
          
        <h1>GeeksforGeeks</h1
        <h2>DOM getElementById() Method</h2
          
        <h3 id="geeks">Hello Geeks!</h3>
          
        <!-- Click here to change content -->
        <input type = "button" onclick = "geeks()"
            value="Click here to change content" /> 
    </body
</html>                    

Output:
Before click on the button:

After click on the button:

Supported Browsers: The browser supported by DOM getElementById() method are listed below:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Opera
  • Safari
My Personal Notes arrow_drop_up
Recommended Articles
Page :