HTML - DOM Document createAttribute() Method
HTML DOM document createAttribute() method is used to create an attribute with a specific name using JavaScript for an HTML element and return the Attr object.
Syntax
document.createAttribute(name);
Parameter
It accepts one required parameter which is mentioned below.
| Parameter | Description |
|---|---|
| name | It represents name of the attribute which you want to create. For invalid name it throws InvalidCharacterError. Invalid name includes starting with a number, hyphen or contains characters other than alphanumeric characters, underscores, hyphens, or periods. |
Return value
It returns a node created using createAttribute() Method.
Examples of HTML DOM Document 'createAttribute()' Method
Here are some examples illustrating use of createAttribute() Method.
Adding href to anchor Tag
In the following example, href is added to anchor tag.
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM Document createAttribute() Method</title>
</head>
<body>
<h3>HTML DOM Document createAttribute() Method</h3>
<a id="attr">Welcome to TutorialsPoint</a>
<br>
<button onclick="fun()">Click me</button>
<script>
function fun(){
let x=document.createAttribute("href");
x.value="https://www.tutorialspoint.com/index.htm"
document.getElementById("attr").setAttributeNode(x);
}
</script>
</body>
</html>
Adding a class to Paragraph
In the following example, we have created a class and added it to a <p> to change the font color of the text.
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM Document createAttribute() Method</title>
<style>
.classone {
color: #04af2f;
}
</style>
</head>
<body>
<h3>HTML DOM Document createAttribute() Method</h3>
<p id="attr">Welcome to TutorialsPoint</p><br>
<button onclick="fun()">Click me</button>
<script>
function fun() {
let x = document.createAttribute("class");
x.value = "classone"
document.getElementById("attr").setAttributeNode(x);
}
</script>
</body>
</html>
Adding Style to Paragraph
In the following example, we have added style to a <p> to change the font color of the text.
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM Document createAttribute() Method</title>
<style>
.classone {
color: #04af2f;
}
</style>
</head>
<body>
<h3>HTML DOM Document createAttribute() Method</h3>
<p id="attr">Welcome to TutorialsPoint</p><br>
<button onclick="fun()">Click me</button>
<script>
function fun() {
let x = document.createAttribute("style");
x.value = "color :#04af2f";
document.getElementById("attr").setAttributeNode(x);
}
</script>
</body>
</html>
Supported Browsers
| Method | ![]() |
![]() |
![]() |
![]() |
![]() |
|---|---|---|---|---|---|
| createAttribute() | Yes 1 | Yes 12 | Yes 44 | Yes 1 | Yes 12.1 |
html_dom.htm
Advertisements




