The createAttribute()
method creates an attribute from
the specified name, and returns the attribute as an Attr object.
createAttribute |
Yes | Yes | Yes | Yes | Yes |
document.createAttribute(attributename)
Parameter | Type | Description |
---|---|---|
attributename | Attr object | Required. The name of the attribute you want to create |
Type | Description |
---|---|
Node object | The created attribute |
The following code shows how to create a class attribute, with the value "democlass", and insert it to an H1 element.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.democlass{<!--from w w w .j av a 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 code above is rendered as follows: