How to Get the Data Attribute in JavaScript?

In this post, I would like to share some simple methods in JavaScript to get an element by data attribute. We are going to use the dataset property to get the data attribute using plain JavaScript and attr() method to get the attribute in jQuery.

1. Using Pure Javascript

In this example, we are going to get the value of the data-url attribute using vanilla JavaScript. There are two ways to achieve that.

Method 1: Using dataset Property

Every HTML element has the dataset property which is used to retrieve the value of the data-* attributes.



Method 2: Using getAttribute() Method

JavaScript getAttribute() method is also one of the built-in methods of HTML elements. We can get any attribute value by using this method.



2. Using jQuery




The first method is easy to implement and is very widely used. I suggest it too because it is a pure JavaScript way of getting a data attribute.