Javascript DOM HTML document createAttribute() Method

Introduction

Create a class attribute, with the value democlass, and insert it to an <h1> element:

Click the button to create a "class" attribute with the value democlass and insert it to the H1 element above.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.democlass {/*  w w  w .ja  va  2 s .c  om*/
  color: red;
}
</style>
</head>
<body>

<h1>Hello World</h1>
<button onclick="myFunction()">Test</button>

<script>
function myFunction() {
  var h1 = document.getElementsByTagName("H1")[0];
  var att = document.createAttribute("class");
  att.value = "democlass";
  h1.setAttributeNode(att);
}
</script>

</body>
</html>

The createAttribute() method creates an attribute by name, and returns the attribute as an Attr object.

Use the attribute.value property to set the value of the attribute.

Use the element.setAttributeNode() method to add the newly created attribute to an element.

document.createAttribute(attributename);

Parameter Values

Parameter TypeDescription
attributename Attr object Required. The name of the attribute you want to create

The createAttribute() method returns a Node object representing the created attribute.




PreviousNext

Related