HTML DOM Element setAttributeNode() method

Definition and Usage

setAttributeNode() This method adds the specified attribute node to the element and returns the Attribute object.

If this specified attribute already exists, this method will replace it.

Alternative solution:

Use setAttribute() method Easier.

See also:

Reference Manual:

getAttributeNode() method

removeAttributeNode() method

createAttribute() method

getAttribute() method

setAttribute() method

hasAttribute() method

Attribute value attribute

HTML DOM Attribute Object

Tutorial:

HTML Attribute

The difference between setAttribute() and setAttributeNode()

setAttribute() Method to replace the attribute value.

setAttributeNode() Method to replace the Attribute object.

Before adding the attribute to the element, you must create an Attr object and set the Attr value.

The result will be the same.

Instance

Example 1

Set the class attribute node of the first <h1> element:

const attr = document.createAttribute("class");
attr.value = "democlass";
const h1 = document.getElementsByTagName("H1")[0];
h1.setAttributeNode(attr);

Try it yourself

Before setting:

Hello World

After setting:

Hello World

Example 2

Set the href attribute node of the <a> element:

const attr = document.createAttribute("href");
attr.value = "";
const anchor = document.getElementById("myAnchor");
anchor.setAttributeNode(attr);

Try it yourself

Before setting:

Please visit codew3c.com

After setting:

Please visit codew3c.com

Syntax

element.setAttributeNode(newAttr)

Parameter

Parameter Description
newAttr Required. Represents the Attr node to be added, or the attribute whose value needs to be modified.

Return value

Type Description
Object

Represents the Attr object of the replaced attribute node.

If no attribute is replaced, it is null.

Throw

This method will throw a DOMException exception containing the following code:

Exception Description
INUSE_ATTRIBUTE_ERR newAttr It is already a member of the attribute set of another Element node.
NO_MODIFICATION_ALLOWED_ERR The current Element node is read-only and its properties cannot be modified.
WRONG_DOCUMENT_ERR newAttr The ownerDocument property is different from the Element node to be set.

Browser support

element.setAttributeNode() It is a DOM Level 1 (1998) feature.

All browsers fully support it:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9-11 Support Support Support Support