Open In App

HTML DOM setAttributeNode() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The setAttributeNode() method in HTML DOM is used to add the specified attribute node to an element. If the specified attribute is already present, then this method replaces it. 

Syntax:

element.setAttributeNode(name)

Parameter: Only one parameter is accepted name.Where the name is the attribute node to be added. It is the required field. 

Return Value: This method returns an attribute object which represents the replaced attribute node otherwise it returns null.

Example: In this example, we will use the setAttributeNode() method.

HTML




<!DOCTYPE html>
<html>
   
<head>
    <title>
        HTML DOM setAttributeNode Method
    </title>
    <style>
        .gfg {
            color: green;
        }
    </style>
</head>
   
<body style="text-align: center;">
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
    <h2>
        DOM setAttributeNode Method
    </h2>
    <p id="p">
        A computer science portal for geeks.
    </p>
    <button onclick="Geeks()">
        Click Here!
    </button>
   
    <script>
        function Geeks() {
           
            //Get the paragraph to add attribute.
            let doc = document.getElementById("p");
           
            //Creating a class attribute.
            let attr = document.createAttribute("class");
 
            //Setting the value of class attribute.
            attr.value = "gfg";
           
            //Adding class attribute to paragraph.
            doc.setAttributeNode(attr);
        }
    </script>
</body>
   
</html>


Output: 

 

Supported Browsers: The browser supported by the setAttributeNode() method are listed below:

  • Google Chrome 1
  • Edge 12
  • Internet Explorer 6
  • Firefox 1
  • Opera 12.1
  • Safari 1


Last Updated : 15 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads