Jashwant
Jashwant

Reputation: 29005

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

Upvotes: 4

Views: 1062

Answers (3)

The Alpha
The Alpha

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);

Use

var data = $('div').draggable().getDataAttr();
console.log(data); // {data-name: "jashwant", data-sex: "male"}

DEMO.

Upvotes: 2

mastaBlasta
mastaBlasta

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

Explosion Pills
Explosion Pills

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;

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

Upvotes: 2

Related Questions