JavaScript DOM Get Set Attributes

In this tutorial you will learn how to get, set and remove attributes from HTML elements in JavaScript.

Working with Attributes

The attributes are special words used inside the start tag of an HTML element to control the tag's behavior or provides additional information about the tag.

JavaScript provides several methods for adding, removing or changing an HTML element's attribute. In the following sections we will learn about these methods in detail.

Getting Element's Attribute Value

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. Here's an example:

<a href="" target="_blank" id="myLink">Google</a>

    // Selecting the element by ID attribute
    var link = document.getElementById("myLink");
    // Getting the attributes values
    var href = link.getAttribute("href");
    alert(href); // Outputs:
    var target = link.getAttribute("target");
    alert(target); // Outputs: _blank

JavaScript provides several different ways to select elements on a page. Please check out the JavaScript DOM selectors chapter to learn more about them.

Setting Attributes on Elements

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.

<button type="button" id="myBtn">Click Me</button>

    // Selecting the element
    var btn = document.getElementById("myBtn");
    // Setting new attributes
    btn.setAttribute("class", "click-btn");
    btn.setAttribute("disabled", "");

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>

    // Selecting the element
    var link = document.getElementById("myLink");
    // Changing the href attribute value
    link.setAttribute("href", "");

Removing Attributes from Elements

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.

<a href="" id="myLink">Google</a>

    // Selecting the element
    var link = document.getElementById("myLink");
    // Removing the href attribute

Your Feedback:

We would love to hear from you, please drop us a line.