The setAttributeNode()
method adds the specified attribute node to an element.
If the attribute exists, this method replaces it.
setAttributeNode |
Yes | Yes | Yes | Yes | Yes |
element.setAttributeNode(attributenode)
Parameter | Type | Description |
---|---|---|
attributenode | Attr object | Required. The attribute node you want to add |
It returns the replaced attribute node as Attr object if any, otherwise null.
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: