The attributes describe the behavior or provides additional information about the tag.
JavaScript provides various kind of methods for adding, removing or changing an HTML element's attribute. In the following sections we will learn about these methods in detail.
The getAttribute() method is used to get the current value of a attribute on the element. If the specified attribute does not exist on the element, it will return null.
Example of Code
<p><a href="https://www.google.com/" target="_blank" id="myLink">Google</a></p>
<script>
// Selecting the element by ID attribute
var link = document.getElementById("myLink");
// Getting the attributes values
var href = link.getAttribute("href");
document.write(href); // Prints: https://www.google.com/
document.write("<br>");
var target = link.getAttribute("target");
document.write(target); // Prints: _blank
</script>
Output
The setAttribute() method is used to set an attribute on the specified element.
If the attribute already exists on the element, the value is updated; otherwise a new attribute is added with the specified name and value. The JavaScript code in the following example will add a class and a disabled attribute to the <button> element.
Example of Code
<button type="button" id="myBtn">Click Me</button>
<script>
// Selecting the element
var btn = document.getElementById("myBtn");
// Setting new attributes
btn.setAttribute("class", "click-btn");
btn.setAttribute("disabled", "");
</script>
Output
The removeAttribute() method is used to remove an attribute from the specified element. The JavaScript code in the following example will remove the href attribute from an anchor element.
Example of Code
<a href="https://www.google.com/" id="myLink">Google</a>
<script>
// Selecting the element
var link = document.getElementById("myLink");
// Removing the href attribute
link.removeAttribute("href");
</script>
Output
Google