HTML DOM Document createAttribute()
Examples
// Create a class attribute:
const att = document.createAttribute("class");
// Set the value of the class attribute:
att.value = "democlass";
// Add the class attribute to the first h1:
const h1 = document.getElementsByTagName("H1")[0];
h1.setAttributeNode(att);
Try it Yourself »
// Create a style attribute:
const att = document.createAttribute("style");
// Set the value of the style attribute:
att.value = "color:red";
// Add the style attribute to the first h1:
const h1 = document.getElementsByTagName("h1")[0];
h1.setAttributeNode(att);
Try it Yourself »
More examples below.
Description
The createAttribute()
method creates an attribute and returns the attribute as an Attr object.
Alternative:
It is easier to use the The setAttribute() Method.
See Also:
Syntax
document.createAttribute(name)
Parameters
Parameter | Description |
name | Required. The name of the attribute to create. |
Return Value
Type | Description |
Node | The created attribute node. |
More Examples
Add a href="www.w3schools.com" attribute an anchor element:
// Create a href attribute:
const att = document.createAttribute("href");
// Set the value of the href attribute:
att.value = "https://www.w3schools.com";
// Add the href attribute to an element:
element.setAttributeNode(att);
Try it Yourself »
Browser Support
document.createAttribute()
is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.