Document: createAttribute() method
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The createAttribute() method of the Document interface creates a new attribute node.
The object created is a node implementing the Attr interface.
The DOM does not enforce what sort of attributes can be added to a particular element in this manner.
Note: The string given in parameter is converted to lowercase.
Syntax
createAttribute(localName)
Parameters
Return value
An Attr node.
Exceptions
InvalidCharacterErrorDOMException-
Thrown if the
localNamevalue is not a valid attribute name. It must have at least 1 character, and may not contain ASCII whitespace,NULL,/,=or>(U+0000, U+002F, U+003D or U+003E, respectively).Note: Earlier versions of the specification were more restrictive, requiring that the
localNamebe a valid XML name.
Examples
>Basic example
const node = document.getElementById("div1");
const a = document.createAttribute("my_attrib");
a.value = "newVal";
node.setAttributeNode(a);
console.log(node.getAttribute("my_attrib")); // "newVal"
Specifications
| Specification |
|---|
| DOM> # dom-document-createattribute> |