How to get the data-id attribute in jquery and javascript?

This tutorial shows the way to get data attribute values in Javascript and jquery with examples.

data-attributes are used to store the custom data to an HTML element.

It can be applied to any valid HTML element including div, span, input, and buttons.

data attributes are defined with valid syntax.

<element data-{validstring}="value"></element>

validstring is a small case string, the “currentAge” string is not valid currentage is valid. value can be any number or string.

Javascript to get data-id attribute example

Javascript DOM API provides selectors to access Element from a DOM Tree.

For example,

<span id="myspan" data-age="30">Age is 30</span>

First, Get html element using id selector function getElementById(). Call getAttribute() method on returned element.

Here is javascript to retrieve data attribute values.

var myspan = document.getElementById("myspan");
var age = myspan.getAttribute("data-age");
console.log(age); // 30

Another way using querySelector

First, select an element document.querySelector with id selector. It returns the element, calling element.dataset.property return value of a data-id attribute.

var myspan = document.querySelector("#myspan");
console.log(myspan.dataset.age);

JQuery to get data attribute value for HTML element

Let’s declare an HTML elements with data-id attributes.

<button type="button" id="submit" data-submit-id="formsubmit">Submit</button>
<span id="myspan" data-age="30">Age is 30</span>

First, select an element using jquery id selectory ($(“#submit”)) data(attribute) returns value.

$("#submit").data("submit-id"); //formsubmit

data() function takes input data submit-id instead of data-submit-id. Another way, use the attr() function

$("#submit").attr("data-submit-id"); //formsubmit
$("#myspan").attr("data-age"); // 30

attr() function takes input data-submit-id instead.

Conclusion

In a summary, Learn multiple ways to get data-id value from HTML elements in javascript and jquery examples