jQuery.data() : Get only HTML-5 attributes and not the data-store values set by jquery or other plugins

StackOverflow https://stackoverflow.com/questions/15346037

  •  23-03-2022
  •  | 
  •  

Question

I want to grab HTML-5 data attributes via jQuery.

So, I am using .data().

I need to fetch more than 1 data attribute, so I am not specifying any parameter and caching the result.

var data = $('myselecttor').data()

But the problem is that .data() not only fetches the HTML-5 attribute but also fetches the data-store values set by jquery (for internal use) or some other plugin (jquery-ui in my case)

Demo

I need to fetch all the HTML-5 data attributes (excluding the data-store values) in one call (not separately)

p.s. sending this data() in $.ajax causes Uncaught TypeError: Illegal invocation error.

I hope, it will help somebody.


My solution

Finally, I am saving all my data-attributes in one data-attribute as a json. jQuery helps in it by automatically parsing any json in data-attribute.

<div data-person='{"name": "jashwant","sex": "male"}'></div>

and can access it in javascript as

 var person =  $('div').data('person');
 console.log(person.name);  // jashwant
 console.log(person.sex);   // male

Only problem is that now I cannot use css selectors like [data-name="jashwant"]

Was it helpful?

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/

OTHER TIPS

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.

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]);
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top