Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 839
Argiropoulos Stavros Avatar asked Feb 29 '12 13:02

Argiropoulos Stavros


People also ask

How do I select an element with a data attribute?

Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.

Which jQuery selector is used to retrieve all elements with the attribute data attribute name?

You can use the attribute selector: $('[data-my-key]').

How do you check if data attribute exists in jQuery?

The jQuery. hasData() method provides a way to determine if an element currently has any values that were set using jQuery. data() . If there is no data object associated with an element, the method returns false ; otherwise it returns true .


2 Answers

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; }); 
like image 193
Nicola Peluchetti Avatar answered Sep 29 '22 06:09

Nicola Peluchetti


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.

like image 36
Ashkan Mobayen Khiabani Avatar answered Sep 29 '22 05:09

Ashkan Mobayen Khiabani