Let’s discuss each of these in detail.
1. Get Attribute
As the name suggests the getAttribute() method is to extract the current value of the attribute. The syntax of the getAttribute() method is as follows.
Syntax of getAttribute() method
Lets see example to further understanding.
Suppose, you want to change src attribute value of <img> element.
The above code shows a Nature picture.
Now we want to change this dog image to a cat image. We use the following code.
The full example with output is shown below.
2. Set Attribute
In order to set an attribute on a specific element, we use the setAttribute() method. It updates the value of an attribute existing on an element or sets a new attribute with a new name and value on an element if one does not exist. The syntax of this method is as follows.
Syntax of setAttribute ( ) method
Let’s see an example to better understand the method.
First we create a simple button with a label of “Click here”.
Now we have to select the <button> element and we will do that using its id.
Now we will use the setAttribute ( ) method to set new attributes.
btn.setAttribute("enable", " ");
The full code alongwith output is shown below.
<button type="button" id="mybtn">Click here</button>
var btn = document.getElementById("myBtn"); //This selects an element
btn.setAttribute("class", "click-btn"); //This set new attributes
btn.setAttribute("enable", " "); //This sets new attributes
To change the attribute value of an HTML element HTML DOM provides two methods which are getAttribute() and setAttribute(). The getAttribute() is used to extract the current value of the attribute while setAttribute() is used to alter the value of the attribute. In this tutorial both of these methods are discussed in detail along with suitable examples.