Javascript Reference - HTML DOM setNamedItem() Method








The setNamedItem() method adds new node to the nodeMap or replace the existing one.

Browser Support

setNamedItem Yes Yes Yes Yes Yes

Syntax

attr.setNamedItem(node);

Parameters

Parameter Type Description
node Node object Required. The node to add or replace




Return Value

Type Description
Node object The replaced node, if any, otherwise null.

Example

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: