Skip to content
Related Articles

Related Articles

HTML DOM getAttribute() Method

View Discussion
Improve Article
Save Article
  • Last Updated : 22 Nov, 2021

In this article, we will learn about the HTML DOM getAttribute() method, along with understanding their implementation through the example.

HTML DOM getAttribute() method is used to get the value of the attribute of the element. By specifying the name of the attribute, it can get the value of that element. To get the values from non-standard attributes, we can use the getAttribute() method.

Syntax:

Object.getAttribute(attributename)

Parameter value:

  • attributename: It is a required parameter with string type that specifies the name of the attribute that needs to retrieve the value.

Return value: It returns the value of a specified attribute on the element. It will return a null or an empty string if the specified attribute doesn’t exist.

Example 1: This example illustrates the DOM getAttribute() method that specifies the value of the attribute for the specified name, of an element.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>DOM getAttribute() Method</title>
</head>
 
<body>
    <center>
        <h1 style="color:green;width:50%;">
            GeeksforGeeks
        </h1>
        <h2>DOM getAttribute() Method</h2>
        <br>
        <button id="button" onclick="geeks()">Submit</button>
        <p id="gfg"></p>
 
         
        <script>
        function geeks() {
            var rk =
            document.getElementById("button").getAttribute("onClick");
            document.getElementById("gfg").innerHTML = rk;
        }
        </script>
    </center>
</body>
 
</html>

Output:

DOM getAttribute() Method

Example 2: This example illustrates the DOM getAttribute() method to retrieve the href attribute value of an element.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>DOM getAttribute() Method</title>
</head>
 
<body>
    <center>
        <h1 style="color:green;width:50%;">
                GeeksforGeeks
            </h1>
        <h2>DOM getAttribute() Method</h2>
        <a id="gfg" href="www.geeksforgeeks.com">
          GeeksforGeeks
        </a>
        <br>
        <br>
        <button id="button" onclick="geeks()">Submit</button>
        <br>
        <p id="rk"></p>
 
         
        <script>
        function geeks() {
            var rk = document.getElementById("gfg").getAttribute("href");
            document.getElementById("rk").innerHTML = rk;
        }
        </script>
    </center>
</body>
 
</html>

Output:

DOM getAttribute() Method

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

  • Google Chrome 1.0
  • Internet Explorer 5.0
  • Microsoft Edge 12.0
  • Firefox 1.0
  • Opera 8.0
  • Safari 1.0

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!