Search code examples
jquerydomjquery-uicustom-data-attribute

How to get only HTML attributes and not the data-store values set by jQuery or other plugins


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>

JSFiddle Demo


Solution

  • You could probably look at the attributes themselves, but you can also use the element's dataset.

    var data = $('div').draggable().get(0).dataset;
    

    http://jsfiddle.net/DprgS/1/