HTML - DOM setAttribute() Method



The HTML DOM setAttribute() method is used to add or update attributes for a specified element in the DOM. An attribute in HTML is a special characteristic or property of an HTML element that provides additional information about that element.

If the specified element does not exist, the method will not create the element; instead, it throws an error if you call this method on a non-existent element. To set attributes for an element, you must first ensure that the element must exist in the DOM.

The following interactive example demonstrate the usage of the setAttribute() method for different scenarios −

DOM setAttribute() Method
Welcome to Tutorialspoint..
You are at the right place to learn...
  • If you click the "Add" button, this method will add the "style" attribute to the first paragraph.
  • If you click the "Update" button, this method will update the existing "style" attribute for the first paragraph.

Syntax

Following is the syntax of the HTML DOM setAttribute() method −

element.setAttribute(attributeName, attributeValue);

Parameters

This method accepts two parameters as mentioned below −

Parameter Description
attributeName The name of the attribute you want to set or change.
attributeValue The new value you want to define for the attribute.

Return Value

This method does not return any value.

Example 1: Setting Attribute for an HTML Element

The following program demonstrates the usage of the HTML DOM setAttribute() method to set the style to the

element when the

Example 2: Setting Inline Styles for Div Element

Following is another example of the HTML DOM setAttribute() method. We use this method to change the inline styles of an existing

by setting an attribute −



 
HTML DOM setAttribute()



HTML - DOM Element

setAttribute() Method

Setting Inline Styles

This div has inline Styles. Click below to change my Style!

Example 3: Creating and Setting Attributes on a New Element

The example below shows the usage of the setAttribute() method by creating and setting attributes on a new element. It creates a new

element and appends it to the document body −



 
HTML DOM setAttribute()



HTML - DOM Element

setAttribute() Method

Creates and Sets Attributes on a New Element

Example 4: Setting Class Attribute to Div Element

This example shows the usage of the setAttribute() method by adding a class attribute (highlight) to an existing

when clicking a button −




HTML DOM setAttribute()


    

HTML - DOM Element

setAttribute() Method

Click button to apply class Attribute

This div has class "container".

Supported Browsers

Method Chrome Edge Firefox Safari Opera
setAttribute() Yes Yes Yes Yes Yes
html_dom_element_reference.htm
Advertisements