Latest web development tutorials
 

HTML DOM setAttributeNode() Method

< 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.w3ii.com";            // Set the value of the href attribute
anchor.setAttributeNode(att);                      // Add the href attribute to <a>

Before setting the attribute node:

Go to w3ii.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: href="met_element_setattribute.html">setAttribute() Method

HTML DOM Reference: href="met_document_createattribute.html">document.createAttribute() Method

HTML DOM Reference: attribute.value Property

HTML DOM Reference: href="met_element_getattributenode.html">getAttributeNode() Method

HTML DOM Reference: href="met_element_removeattributenode.html">removeAttributeNode() Method


< Element Object