Javascript DOM HTML NamedNodeMap setNamedItem() Method

Introduction

Set a H1's class attribute:

Click the button to set the H1's class attribute to *democlass".

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.democlass {// w w  w .  j  a  v a 2s.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.value = "democlass";
  h.attributes.setNamedItem(typ);
}
</script>

</body>
</html>

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

If the node exists, it will be replaced, and the replaced node will be the return value, otherwise the return value will be null.

setNamedItem(node); 

Parameter Values

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

The setNamedItem() method returns a Node object representing the replaced node, otherwise null.




PreviousNext

Related