How to manipulate attributes in vanilla JS

In jQuery, you can use the attr() and removeAttr() methods to manipulate an HTML element’s attributes. These methods really are redundant these days. You can do this so easily in vanilla JS with full support back to IE8.

Getting attributes

To get the value of an attribute, you can use the getAttribute() method.

You pass in a string for the attribute you want to get.

If the attribute doesn’t exist, this method returns null.

// Get the element with the ID "cup"
var cup = document.querySelector("#cup");

// Get the value of its "data-drink" attribute
var drink = cup.getAttribute("data-drink");

Setting attributes

To set the value of an attribute, you can use the setAttribute() method.

You pass in two strings: one for the attribute, and another for its value.

// Get the element with the ID "cup"
var cup = document.querySelector("#cup");

// Set the value of its "data-drink" attribute
cup.setAttribute("data-drink", "coffee");

Removing attributes

To remove an attribute, you can use the removeAttribute() method.

You pass in a string for the attribute you want to remove.

If the attribute doesn’t exist, this method fails silently.

// Get the element with the ID "cup"
var cup = document.querySelector("#cup");

// Remove its "data-drink" attribute
cup.removeAttribute("data-drink");

Checking if an attribute exists

To check if an attribute exists, you can use the hasAttribute() method.

You pass in a string for the attribute you want to check.

This method always returns a boolean value: true or false.

// Get the element with the ID "cup"
var cup = document.querySelector("#cup");

// Check if it has the "data-drink" attribute
if (cup.hasAttribute("data-drink")) {
  console.log("The attribute exists");
}

Summary

The following are native and well-supported replacements for jQuery’s attr() and removeAttr() methods:

I’ve used data-* attributes in this post, but these methods work with all attributes.


If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!