HTML DOM createAttribute() method


The HTML DOM createAttribute() method is used for creating a specific attribute using JavaScript for an HTML element. The createAttribute() method creates an attribute with the given name and returns the attribute as an Attr object.

Syntax

Following is the syntax for createAttribute() method −

document.createAttribute(attributename)

Example

Let us look at an example for the HTML DOM createAttribute() method −

<!DOCTYPE html>
<html>
<head>
<title>CREATE ATTRIBUTE</title>
<style>
   #DIV1{
      margin-top:15px;
      width:250px;
      height:200px;
      border:2px solid blue;
      background-color:lightgreen;
   }
</style>
</head>
<body>
<p>Click the button to create a "class" attribute for the div element</p>
<button onclick="attrCreate()">CREATE</button>
<br>
<div>
<p>This is a sample div</p>
</div>
<script>
   function attrCreate() {
      var x = document.getElementsByTagName("div")[0];
      var att = document.createAttribute("id");
      att.value = "DIV1";
      x.setAttributeNode(att);
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking the CREATE button −

In the above example −

We have created a style with id “DIV1”

#DIV1{
   margin-top:15px;
   width:250px;
   height:200px;
   border:2px solid blue;
   background-color:lightgreen;
}

We have then created a <div> element that has a <p> element inside it.

<div>
<p>This is a sample div</p>
</div>

Then, we have created a button CREATE that will execute attrCreate() function when clicked by a user −

<button onclick="attrCreate()">CREATE</button>

The attrCreate() function gets the <div> element using the getElementsByTagName() method on the document object and assigns it to the variable x. Using the createAttribute() method we create the “id” attribute and using its value property assigns it the value “DIV1”, which is the id of the style we created previously. Finally, we set the “id” attribute along with its value to the <div> element −

function attrCreate() {
   var x = document.getElementsByTagName("div")[0];
   var att = document.createAttribute("id");
   att.value = "DIV1";
   x.setAttributeNode(att);
}
raja
Published on 08-Aug-2019 16:33:28
Advertisements