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.
element.setAttribute(Attr_Name, Attr_Value)
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.Let us write a code to set an attribute and its value to an element.
5
, we set the color property of the CSS class new
to ‘yellow’.12
, we have a DIV
element with id div
, to which we will add the new CSS.14
, we have a paragraph tag with text.16
, we write a button tag with a change()
function that will be called when the user clicks on it.19
, we write the JavaScript code in the script tag. We define a change()
function that will be called when a user clicks on the button from the HTML page.20
, we use getElementById()
and pass id div
to get the div
element.21
, we use the setAttribute()
method on the element object above to add the new attribute and its value in the DIV
element.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.