Javascript Reference - HTML DOM setAttributeNode() Method








The setAttributeNode() method adds the specified attribute node to an element.

If the attribute exists, this method replaces it.

Browser Support

setAttributeNode Yes Yes Yes Yes Yes

Syntax

element.setAttributeNode(attributenode)

Parameters

Parameter Type Description
attributenode Attr object Required. The attribute node you want to add




Return Value

It returns the replaced attribute node as Attr object if any, otherwise null.

Example

The following code shows how to set the class attribute node of a header element.


<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.democlass{<!--  w  w w  .  j ava  2 s .c o m-->
  color:red;
}
</style>
</head>
<body>
<h1>Hello World</h1>
<button onclick="myFunction()">test</button>
<script>
function myFunction()
{
    var atr=document.createAttribute("class");
    atr.nodeValue="democlass";
    var h=document.getElementsByTagName("H1")[0];
    h.setAttributeNode(atr); 
}
</script>

</body>
</html>

The code above is rendered as follows: