Attributes are special words used inside the start tag of an HTML element to control the tag's behavior or provide additional information about the tag.
JavaScript provides several methods for adding, removing, or changing an HTML element's attributes. In the following sections, we will learn about these methods in detail.
The getAttribute()
method is used to get the current value of an attribute on the element.
If the specified attribute does not exist on the element, it will return null
. Here's an example:
<a href="https://www.google.com/" target="_blank" id="myLink">Google</a>
<script>
// Selecting the element by ID attribute
var link = document.getElementById("myLink");
// Getting the attributes values
var href = link.getAttribute("href");
alert(href); // Outputs: https://www.google.com/
var target = link.getAttribute("target");
alert(target); // Outputs: _blank
</script>
JavaScript offers several ways to select elements on a page. To learn more, check out the JavaScript DOM selectors chapter.
The setAttribute()
method is used to set an attribute on the specified element.
If the attribute already exists on the element, its 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.
<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>
Similarly, you can use the setAttribute()
method to update or change the value of an existing attribute on an HTML element. The JavaScript code in the following example will update the value of the existing href
attribute of an anchor (<a>
) element.
<a href="#" id="myLink">Tutorial Republic</a>
<script>
// Selecting the element
var link = document.getElementById("myLink");
// Changing the href attribute value
link.setAttribute("href", "https://www.codinghub360.in");
</script>
The removeAttribute()
method is used to remove an attribute from the specified element.
In the JavaScript code example below, the href
attribute is removed from an anchor element.
<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>