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.
HTML
<a data-url="techieheap.com">click here</a>
JavaScript
const link = document.querySelector('a');
const url = link.dataset.url;
console.log(url); // techieheap.com
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.
HTML
<p data-url="techieheap.com">techieheap</p>
JavaScript
const link = document.querySelector('p');
const url = link.getAttribute("data-url");
console.log(url); // techieheap.com
2. Using jQuery
HTML
<a class="link" data-url="techieheap.com">click here</a>
jQuery
const link = $(".link");
const url = link.attr("data-url");
console.log(url); // techieheap.com
Conclusion
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.