The createAttribute() method creates an attribute with the specified name, and returns the attribute as an Attr object.
Use the attribute.value property to set the value of the attribute and Use the element.setAttributeNode() method to add the newly created attribute to an element.
Syntax and usage
document.createAttribute(attributename)
Parameter Values
attributename Attr object Required. The name of the attribute you want to create
Example(1)
<script>
function myFunction() {
var h1 = document.getElementsByTagName("H2")[0]; // Get the first <h2> element in the document
var att = document.createAttribute("class"); // Create a "class" attribute
att.value = "democlass"; // Set the value of the class attribute
h1.setAttributeNode(att); // Add the class attribute to <h2>
}
</script>
In above example creating a class attribute, with the value "democlass", and insert it to an <h2> element when button is clicked.
Example(2)
<a id="link">A Link:Visit our bajarangisoft site to learn more about Java Script </a>
<button onclick="create_link()">Click it</button>
<script>
function create_link() {
var anchor = document.getElementById("link");
var att = document.createAttribute("href");
att.value = "https://blog.bajarangisoft.com/blogs";
anchor.setAttributeNode(att);
}
</script>
In above example creating a href attribute, with the value "www.w3schools.com", and insert it to an <a> element.
Complete Code For HTML DOM CreateAttribute Method In JavaScript
<!DOCTYPE html>
<html>
<head>
<title>HTML DOM CreateAttribute Method In JavaScript</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<style>
.democlass {
color: red;
}
</style>
<body>
<div class="container">
<br>
<div class="text-center">
<h1>HTML DOM CreateAttribute Method In JavaScript</h1>
</div>
<br>
<div class="well">
<h2>Hello World ! Welocme to Bajarangisoft</h2>
<button class="btn btn-primary" onclick="change_color()">Try it</button>
</div>
<br>
</div>
</body>
</html>
<script>
function change_color() {
var h1 = document.getElementsByTagName("H2")[0]; // Get the first <h2> element in the document
var att = document.createAttribute("class"); // Create a "class" attribute
att.value = "democlass"; // Set the value of the class attribute
h1.setAttributeNode(att); // Add the class attribute to <h2>
}
</script>