Jquery select all elements that have $jquery.data()

Select elements that i have previously set with jquery.data();

i.e. Select all elements with .data('myAttr') already been set.

SOLUTION

A jsfiddle to demostrate is Fiddle


You could do

$('[data-myAttr!=""]'); 

this selects all elements which have an attribute data-myAttr which is not equal to '' (so it must have been set); (only for elements that have their data attribute set in HTML not via jQuery)

you could also use filter() (which works for data attributes set from jQuery)

$('*').filter(function() {
    return $(this).data('myAttr') !== undefined;
});

The best and simple way to select them is:

$('[data-myAttr]')

More Information:

I tested a lot of things.

Using $('[data-myAttr!=""]') doesn't work for all cases. Because elements that do not have a data-myAttr set, will have their data-myAttr equal to undefined and $('[data-myAttr!=""]') will select those as well, which is incorrect.


You can use filter():

var elements = $("*").filter(function() {
    return $(this).data("myAttr") !== undefined;
});

You could use this jQuery Selector extention: Querying element data

$(':data');       // All elements with data  
$(':not(:data)'); // All elements without data