Open In App

HTML DOM setAttribute() Method

The HTML DOM setAttribute() method is used to get the value of the attribute of the element. By specifying the name of the attribute, it can set the value of that element. If the element is already present then its value is updated.

Syntax:



Object.setAttribute(attributename,value)

Parameters: This method accepts two parameters:

Return Values: This parameter does not return any values.



The below examples show the use of the setAttribute() method.

Example 1: In this example, we will add a href attribute to the anchor tag using the setAttribute() method.




<!DOCTYPE html>
<html>
<body>
    <h1 style="color:green">
        Geeks for Geeks
    </h1>
    <h2>setAttribute() Method</h2>
  
    <a id="geek">Click to go to geeksforgeeks.org</a>
  
    <p>
        Click the button below to add an href
        attribute to the element above.
    </p>
  
    <button onclick="myFunction()">Click Me</button>
  
    <script>
        function myFunction() {
          document.getElementById("geek").setAttribute
          ("href", "https://www.geeksforgeeks.org"); 
        }
    </script>
</body>
</html>

Output:

HTML DOM setAttribute() Method

Example 2: In this example, we will change the type of an input tag to a button using the setAttribute() method.




<!DOCTYPE html>
<html>
<body>
    <h1 style="color:green">
        Geeks for Geeks
    </h1>
    <h2>setAttribute() Method</h2>
  
    <input id="geeks" value="Hello Geek">
  
    <p>
        Click the button below to change the
        input field to an input button.
    </p>
    <button onclick="changeType()">Change</button>
  
    <script>
        function changeType() {
          document.getElementById("geeks").setAttribute("type", "button"); 
        }
    </script>
</body>
</html>

Output:

HTML DOM setAttribute() Method

We have a complete list of HTML DOM methods, to check those please go through this HTML DOM Object Complete reference article.

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


Article Tags :