Open In App

HTML DOM setAttribute() Method

Last Updated : 07 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • attributename: It is a string whose value is to be set.
  • value: It is a string value that is to be assigned to the attributename.

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.

HTML




<!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

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.

HTML




<!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

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: 

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


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads