This createAttribute() method is used to create an attribute with the specified name and returns the attribute object. The attribute.value property is used to set the value of the attribute and the element.setAttribute() method is used to create a new attribute for an element. This method() contains the name of the created attribute as a parameter value.Â
Syntax
document.createAttribute( attributename )Example: In this example, we will use the createAttribute() method.
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>DOM createAttribute Method</title>
<style>
.gfg {
color: green;
font-weight: bold;
font-size: 50px;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h2>DOM createAttribute() Method</h2>
<!--Driver Code Ends-->
<button onclick="geeks()">
Submit
</button>
<script>
function geeks() {
let tag_name =
document.getElementsByTagName("h1")[0];
let attr =
document.createAttribute("class");
attr.value = "gfg";
tag_name.setAttributeNode(attr);
}
</script>
<!--Driver Code Starts-->
</body>
</html>
<!--Driver Code Ends-->
Example 2: In this example, we will use the createAttribute() method.
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: green;
}
body {
text-align: center;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h2>DOM createAttribute() Method</h2>
<a id="gfg">
Visit GeeksForGeeks...
</a><br><br>
<button onclick="geeks()">
Submit
</button>
<!--Driver Code Ends-->
<script>
function geeks() {
let id = document.getElementById("gfg");
let new_attr = document.createAttribute("href");
new_attr.value = "#";
id.setAttributeNode(new_attr);
}
</script>
<!--Driver Code Starts-->
</body>
</html>
<!--Driver Code Ends-->
- Creates a standalone Attr node: Unlike setAttribute(), which directly adds a name/value pair to an element, createAttribute() returns an independent Attr object that you can configure (set its .value, inspect properties, etc.) before attaching it with setAttributeNode().
- Name is forced to lowercase: The method automatically converts the attribute name you pass to lowercase, matching HTMLâs case-insensitive attribute handling (this behavior is part of the current DOM specification).