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 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

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

Specification
DOM
# dom-document-createattribute

Browser compatibility

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
createAttribute

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Has more compatibility info.

See also