W3cubDocs

/Web APIs

Document: createAttribute() method

The Document.createAttribute() method creates a new attribute node, and returns it. 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

js

createAttribute(name)

Parameters

  • name is a string containing the name of the attribute.

Return value

A Attr node.

Exceptions

InvalidCharacterError DOMException

Thrown if the name value is not a valid XML name; for example, it starts with a number, hyphen, or period, or contains characters other than alphanumeric characters, underscores, hyphens, or periods.

Examples

js

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

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
createAttribute 1 12 44
1–44The parameter was not converted to its lowercase variant.
6 ≤12.1 1 4.4 18 44
4–44The parameter was not converted to its lowercase variant.
≤12.1 1 1.0

See also

© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Document/createAttribute