HTML DOM Element setAttribute()

Example

Add a class attribute to an element:

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

Before:

The Element Object

After:

The Element Object

Try it Yourself »

More examples below.


Description

The setAttribute() method sets a new value to an attribute.

If the attribute does not exist, it is created first.



Syntax

element.setAttribute(name, value)

Parameters

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

Return Value

NONE

Note

It is possible to add a style attribute with a value to an element, but it is not recommended because it can overwrite other properties in the style attribute.

Use Properties of the Style Object instead:

NO:

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

YES:

element.style.backgroundColor = "red";


More Examples

Change an input field to an input button:

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

Before:

After:

Try it Yourself »

Add a href attribute to an <a> element:

myAnchor.setAttribute("href", "https://www.w3schools.com");

Before:

Go to w3schools.com

After:

Try it Yourself »

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

if (element.hasAttribute("target")) {      
  element.setAttribute("target", "_self");
}
Try it Yourself »

Browser Support

element.setAttribute() is a DOM Level 1 (1998) feature.

It is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.