HTML DOM Element setAttribute() method

Definition and Usage

setAttribute() The method adds the specified attribute and assigns the specified value to it.

If the specified attribute already exists, it will only set or change the value.

Note:The HTMLElement object in the HTML document also defines JavaScript properties corresponding to all standard HTML attributes. Therefore, you only need to use this method when you need to set non-standard attributes.

See also:

Reference Manual:

getAttribute() method

removeAttribute() method

hasAttribute() method

hasAttributes() method

getAttributeNode() method

setAttributeNode() method

removeAttributeNode() method

Tutorial:

HTML Attributes

Instance

Example 1

Add class attribute to the element:

element.setAttribute("class", "democlass");

Before adding:

Element Object

After adding:

Element Object

Try It Yourself

Example 2

Change the input field to a button:

myInput.setAttribute("type", "button");

Try It Yourself

Before changing:

After changing:

Example 3

Add the href attribute to the <a> element:

myAnchor.setAttribute("href", "");

Try It Yourself

Before adding:

Please visit codew3c.com

After adding:

Please visit codew3c.com

Example 4

Change the value of the target attribute to "_self":

if (element.hasAttribute("target")) {      
  element.setAttribute("target", "_self");
}

Try It Yourself

Syntax

element.setAttribute(name, value)

Parameter

Parameter Description
name Required. The name of the attribute.
value Required. The new attribute value.

Return Value

None.

Thrown

Exception Description
INVALID_CHARACTER_ERR Parameter name Characters that are not allowed to be used in HTML attribute names or XML attribute names.
NO_MODIFICATION_ALLOWED_ERR The current element is read-only and its properties cannot be modified.

Note

You can add a style attribute with a value to the element, but it is not recommended to do so as it will override other properties in the style attribute.

Please use the Style object's properties instead:

Disadvantage:

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

Advantage:

element.style.backgroundColor = "red";

Browser Support

element.setAttribute() 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