Reputation: 29005
I want to grab HTML data attributes via jQuery using .data()
.
I need to fetch more than one data attribute, so I am not specifying any parameter and caching the result:
var data = $('myselecttor').data()
The problem is that .data()
fetches not only the HTML attribute, but also the data-store values set by jQuery (for internal use) or some other plugin (jQuery UI in my case).
I need to fetch all the HTML data attributes (excluding the data-store values) in one call (not separately)
Sending this data()
in $.ajax
causes an error:
Uncaught TypeError: Illegal invocation
var data = $('div').draggable().data();
console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.1/jquery-ui.min.js"></script>
<div data-name="jashawant" data-sex="male">Drag me</div>
Upvotes: 4
Views: 1062
Reputation: 146201
You may try this
(function($) {
$.fn.getDataAttr = function() {
var attributes = {};
if( this.length ) {
$.each( this[0].attributes, function( i, attr ) {
if( attr.name.substr(0,5) =='data-' )
attributes[ attr.name ] = attr.value;
} );
}
return attributes;
};
})(jQuery);
var data = $('div').draggable().getDataAttr();
console.log(data); // {data-name: "jashwant", data-sex: "male"}
Upvotes: 2
Reputation: 5850
Couple more options:
Namespace your data attributes
<div id="mydiv" data-jashwant-name="jashwant" data-jashwant-sex="male">Drag me</div>
then loop and select only yours
for (var i in data) {
if (i.indexOf('jashwant') > -1 ) {
console.log(i + " : " + data[i]);
}
}
OR... Less reliable, but might work in this scenario. Only select data attributes whose value is a string (ignore jquery UI objects)
for (var i in data) {
if (typeof data[i] === "string" ) {
console.log(i + " : " + data[i]);
}
}
Upvotes: 0
Reputation: 191749
You could probably look at the attributes themselves, but you can also use the element's dataset
.
var data = $('div').draggable().get(0).dataset;
Upvotes: 2