Javascript DOM HTML Element setAttributeNode() Method add new attribute

Introduction

Set the class attribute node of a <h1> element:

Click the button to set the class attribute node of the header above.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.democlass {/*from w w w  .ja v a  2s.  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>

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

If the specified attribute already exists, this method replaces it.

The return value of this method is an Attr object.

Use the removeAttributeNode() method to remove an attribute node from an element.

element.setAttributeNode(attributenode);

Parameter Values

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

The setAttributeNode() method returns an Attr object, representing the replaced attribute node, if any, otherwise null.




PreviousNext

Related