Element setAttributeNode() Method - Javascript DOM

Javascript examples for DOM:Element setAttributeNode

Description

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

For existing attribute, this method replaces it.

The return value is an Attr object.

Parameter Values

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

Return Value:

An Attr object, representing the replaced attribute node, if any, otherwise null

The following code shows how to Set the class attribute node of a <h1> element:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.democlass {//from   w  w w.  ja v  a  2 s  . c om
    color: red;
}
</style>
</head>
<body>

<h1>Hello World</h1>

<button onclick="myFunction()">Test</button>

<script>
function myFunction() {
    var attr = document.createAttribute("class");
    attr.value = "democlass";
    var h = document.getElementsByTagName("H1")[0];
    h.setAttributeNode(attr);
}
</script>

</body>
</html>

Related Tutorials