HTML | DOM setAttributeNode() Method

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: Onll one parameter is accepted name.Where 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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. 
            var doc = document.getElementById("p");
  
            //Creating a class attribute.
            var attr = document.createAttribute("class");
  
            //Setting the value of class attribute.
            attr.value = "gfg";
  
            //Adding class attribute to paragraph. 
            doc.setAttributeNode(attr);
        }
    </script>
</body>
  
</html>

chevron_right


Output:

Before click on the button:
setAttributeNode

After click on the button:
setAttributeNode

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

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Opera
  • Safari


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.