HTML - DOM Element setAttributeNode() Method



The HTML DOM Element setAttributeNode() method is used to add (or define) an attribute node to a specific element and update any existing attribute node with the same name.

An attribute node in the Document Object Model (DOM) represents an attribute of an element. Attributes provide additional information about an element.

Syntax

Following is the syntax of the HTML DOM Element setAttributeNode() method −

element.setAttributeNode(newAttrNode);

Parameters

This method accepts a single parameter as mentioned below:

Parameter Description
newAttrNode The new node you want to define for the particular element.

Return Value

This method does not always return a value; instead, it sets a new attribute node value for the element. However, if an attribute is updated, it returns an 'Attr' object that holds the updated attribute node.

Example 1: Setting Class Attribute Node on Div Element

The following program demonstrates using the HTML DOM Element setAttributeNode() method. It adds (sets) the class attribute node on a

element −




HTML DOM Element setAttributeNode()



HTML DOM Element setAttributeNode() Method

Click button to set the class attribute to a div element.

The above program adds a class attribute node to a

element.

Example 2: Updating the Attribute Node

Following is another example of the HTML DOM Element setAttributeNode() method. We use this method to update the existing attribute node of an

element −







This is a paragraph element.

Click the below button to update attribute node

When the program is executed, it updates the existing attribute node once the button is clicked.

Example 3: Setting Id Attribute Node on

Element

In the example below, we use this function to add an id attribute node to a

element:




HTML DOM Element setAttributeNode()



HTML DOM Element setAttributeNode() Method

Click button to set the id attribute to a "p" element.

The above program will add an "id" attribute node to a "p" element.

Supported Browsers

Method Chrome Edge Firefox Safari Opera
setAttributeNode() Yes Yes Yes Yes Yes
html_dom.htm
Advertisements