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 provide a means to store custom data within HTML elements. They can be applied to various HTML elements such as div, span, input, and button.
These attributes are defined with a specific syntax:
<element data-{validstring}="value"></element>
Here, validstring must be a lowercase string; for instance, “currentAge” is invalid, while “currentage” is valid. The value can be any number or string.
JavaScript Example Retrieving data-id Attribute
To retrieve a data attribute value in JavaScript, you can use the DOM API along with selectors to access elements from the DOM tree. For instance:
<span id="myspan" data-age="30">Age is 30</span>
You can use getElementById() to get the HTML element and then call getAttribute() to retrieve the data attribute value:
Here is javascript to retrieve data attribute values.
var myspan = document.getElementById("myspan");
var age = myspan.getAttribute("data-age");
console.log(age); // Output: 30
Another approach involves using querySelector:
First, select an element using document.querySelecto
r 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 Example: Retrieving Data Attribute Value for HTML element
In jQuery, you can select an element using its ID and then retrieve the data attribute value using the data() function:
<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
Alternatively, you can use the attr() function:
attr() function takes input data-submit-id instead.
Conclusion
In summary, this tutorial has illustrated various methods for retrieving data-id values from HTML elements using JavaScript and jQuery.