The setNamedItem()
method adds new node to the nodeMap or
replace the existing one.
setNamedItem |
Yes | Yes | Yes | Yes | Yes |
attr.setNamedItem(node);
Parameter | Type | Description |
---|---|---|
node | Node object | Required. The node to add or replace |
Type | Description |
---|---|
Node object | The replaced node, if any, otherwise null. |
The following code shows how to set a H1's class attribute.
<!DOCTYPE html>
<html>
<head>
<style>
.myStyle {<!--from w w w .j a va 2 s . c o m-->
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.nodeValue = "myStyle";
h.attributes.setNamedItem(typ);
}
</script>
</body>
</html>
The code above is rendered as follows: