While working with front-end of any web-application, we may want to select or get and HTML element using data-attribute instead of ID or Class, so in this article, I have mentioned how we can get or select an HTML element using data-attribute in jQuery or Javascript with an example.
Using Javascript
To get an element by its data attribute using JavaScript, you can use the querySelector method with the [data-*]
attribute selector, like this:
const element = document.querySelector('[data-attribute="value"]');
You can replace "attribute" with the name of the data attribute you want to search for, and "value" with the corresponding value.
For example, we have below HTML element
<p data-select="1">Paragrapgh 1</p>
<p data-select="2">Paragrapgh 2</p>
<p data-select="3">Paragrapgh 3</p>
Then to select element with data-select = 2, we can have javascript code as below
const element = document.querySelector('[data-select="2"]');
console.log(element.innerHTML);
//output: Paragrapgh 2
Here is the fiddle link: https://jsfiddle.net/9etm1aL7/
Using jQuery
To get an element by its data attribute using jQuery, you can use the jQuery function with the same attribute selector, like this:
const element = $('[data-attribute="value"]');
you would need to replace "attribute" with the name of the data attribute you want to search for, and "value" with the corresponding value.
So if we consider above HTML example of paragraphs, then to get an paragraph with data-select = 2
then jQuery code would be as below
var element = $('[data-select="2"]');
Both of these methods will return the first element that matches the selector.
If you want to get all matching elements, use querySelectorAll
in Javascript method.
You may also like to read:
Various ways to convert date to Unix Timestamp in Javascript
How can I check Typescript version in Visual Studio?
Various ways to make HTTP Request in Javascript
Google places autocomplete example without Map in Javascript