THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

HTML DOM setAttribute() Method

Element Object Reference Element Object

Example

Add the class attribute with the value of "democlass" to a <h1> element:

document.getElementsByTagName("H1")[0].setAttribute("class", "democlass");

Before setting the attribute:

Hello World

After setting the attribute:

Hello World

Try it Yourself »

More "Try it Yourself" examples below.


Definition and Usage

The setAttribute() method adds the specified attribute to an element, and gives it the specified value.

If the specified attribute already exists, only the value is set/changed.

Note: Although it is possible to add the style attribute with a value to an element with this method, it is recommended that you use properties of the Style object instead for inline styling, because this will not overwrite other CSS properties that may be specified in the style attribute:

Bad:

element.setAttribute("style", "background-color: red;");

Good:

element.style.backgroundColor = "red";

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

Tip: See also the setAttributeNode() method.


Browser Support

The numbers in the table specify the first browser version that fully supports the method.

Method
setAttribute() Yes 9.0 Yes Yes Yes

Syntax

element.setAttribute(attributename,attributevalue)

Parameter Values

Parameter Type Description
attributename String Required. The name of the attribute you want to add
attributevalue String Required. The value of the attribute you want to add

Technical Details

Return Value: No return value
DOM Version Core Level 1 Element Object

Examples

More Examples

Example

Change an input field to an input button:

document.getElementsByTagName("INPUT")[0].setAttribute("type", "button");

Before setting the attribute:

After setting the attribute:

Try it Yourself »

Example

Add a href attribute with a value of "www.w3schools.com" to an <a> element:

document.getElementById("myAnchor").setAttribute("href", "http://www.w3schools.com");

Before setting the attribute:

Go to w3schools.com

After setting the attribute:

Try it Yourself »

Example

Find out if an <a> element has a target attribute. If so, change the value of the target attribute to "_self":

// Get the <a> element with id="myAnchor"
var x = document.getElementById("myAnchor"); 

// If the <a> element has a target attribute, set the value to "_self"
if (x.hasAttribute("target")) {      
    x.setAttribute("target", "_self");
}
Try it Yourself »

Related Pages

HTML Tutorial: HTML Attributes

HTML DOM Reference: getAttribute() Method

HTML DOM Reference: hasAttribute() Method

HTML DOM Reference: removeAttribute() Method


Element Object Reference Element Object