HTML DOM Document createAttribute() method
- Previous page cookie
- Next page createComment()
- Return to the Previous Level HTML DOM Documents
Definition and usage
code>createAttribute() The method creates an attribute and returns it as an Attr object.
Alternative:
Use setAttribute() method Easier.
See also:
Instance
Example 1
// Create the 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);
Example 2
// Create the 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);
Example 3
Add the href="www.codew3c.com" attribute to the anchor element:
// Create the href attribute: const att = document.createAttribute("href"); // Set the value of the href attribute: att.value = "https://www.codew3c.com"; // Add the href attribute to the element: element.setAttributeNode(att);
Syntax
document.createAttribute(name)
parameter
parameter | description |
---|---|
name | required. The name of the attribute to be created. |
return value
type | description |
---|---|
node | The newly created attribute node. The nadeName attribute is set to name. |
throw
If the name contains invalid characters, this method will throw a code of INVALID_CHARACTER_ERR
of the DOMException exception.
Browser support
document.createAttribute()
It is a DOM Level 1 (1998) feature.
It is supported by all browsers:
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
Support | 9-11 | Support | Support | Support | Support |
- Previous page cookie
- Next page createComment()
- Return to the Previous Level HTML DOM Documents