Attribute setNamedItem() Method - Javascript DOM

Javascript examples for DOM:Attribute

Description

The setNamedItem() method adds the node to the NamedNodeMap.

For existing node, it will be replaced, and the replaced node will be the return value, otherwise null is returned.

Parameter Values

Parameter TypeDescription
node Node object Required. The node to add/replace in the NamedNodeMap collection

Return Value:

A Node object, representing the replaced node (if any), otherwise null

The following code shows how to Set a H1's class attribute:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.democlass {/*from w w  w.j a  v  a2  s.  com*/
    color: red;
}
</style>
</head>
<body>

<h1>Hello World</h1>

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

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

</body>
</html>

Related Tutorials