What is the setAttribute() method in DOM?
Overview
In this shot, we will learn how to add a new attribute and its value in an HTML element.
The setAttribute() method sets the attribute and its value (passed as a parameter) to the element it is applied on.
If there is already an attribute with the same name, setAttribute() will change or replace the value.
Syntax
element.setAttribute(Attr_Name, Attr_Value)
Parameters
Attr_Name: The name of the attribute we want to add to the element, i.e.,class.Attr_Value: The value for the specified attribute.
Code
Let us write a code to set an attribute and its value to an element.
Code explanation
- In line
5, we set the color property of the CSS classnewto ‘yellow’. - In line
12, we have aDIVelement with iddiv, to which we will add the new CSS. - In line
14, we have a paragraph tag with text. - In line
16, we write a button tag with achange()function that will be called when the user clicks on it. - In line
19, we write the JavaScript code in the script tag. We define achange()function that will be called when a user clicks on the button from the HTML page. - In line
20, we usegetElementById()and pass iddivto get thedivelement. - In line
21, we use thesetAttribute()method on the element object above to add the new attribute and its value in theDIVelement.
Output
When we click the button, the color of the DIV element changes, which means the new CSS class has been successfully added to the selected DIV element.