THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

HTML DOM setAttributeNode() Method

Element Object Reference Element Object

Example

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

var h1 = document.getElementsByTagName("H1")[0];   // Get the first <h1> element in the document
var att = document.createAttribute("class");       // Create a "class" attribute
att.value = "democlass";                           // Set the value of the class attribute
h1.setAttributeNode(att);                          // Add the class attribute to <h1>

Before setting the attribute node:

Hello World

After setting the attribute node:

Hello World

Try it yourself »

More "Try it Yourself" examples below.


Definition and Usage

The setAttributeNode() method adds the specified attribute node to an element.

If the specified attribute already exists, this method replaces it.

The return value of this method is an Attr object. For more information, see The HTML DOM Attribute Object.

See also the setAttribute() method.

Tip: Use the removeAttributeNode() method to remove an attribute node from an element.


Browser Support

Method
setAttributeNode() Yes Yes Yes Yes Yes

Syntax

element.setAttributeNode(attributenode)

Parameter Values

Parameter Type Description
attributenode Attr object Required. The attribute node you want to add

Technical Details

Return Value: An Attr object, representing the replaced attribute node, if any, otherwise null
DOM Version Core Level 1 Element Object

Examples

More Examples

Example

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

var anchor = document.getElementById("myAnchor");  // Get the <a> element with id="myAnchor"
var att = document.createAttribute("href");        // Create a "href" attribute
att.value = "http://www.w3schools.com";            // Set the value of the href attribute
anchor.setAttributeNode(att);                      // Add the href attribute to <a>

Before setting the attribute node:

Go to w3schools.com

After setting the attribute node:

Try it yourself »

Related Pages

HTML Tutorial: HTML Attributes

HTML DOM Reference: The HTML DOM Attribute Object

HTML DOM Reference: setAttribute() Method

HTML DOM Reference: document.createAttribute() Method

HTML DOM Reference: attribute.value Property

HTML DOM Reference: getAttributeNode() Method

HTML DOM Reference: removeAttributeNode() Method


Element Object Reference Element Object