Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery get all elements matching data attribute name

Tags:

jquery

say i have a few elements with the following data attribute:

<data-my-key="blah">

and i want to attach an event to them all, how can this be done?

I have tried a few things but cant get it to work.

My latest attempt was:

$('data-my-key').click(...

and

$(document).find('data-my-key').click(...
like image 979
Marty Wallace Avatar asked Nov 20 '13 09:11

Marty Wallace


2 Answers

You can use the attribute selector:

$('[data-my-key]').click(... 

Note however, that jQuery stores data attributes added after DOM load in it's internal cache not as an attribute on the element, so that selector would not work for those. In that case you would need to use filter:

$(document).children().filter(function() {     return $(this).data('my-key'); }).click(...; 
like image 184
Rory McCrossan Avatar answered Sep 19 '22 08:09

Rory McCrossan


You can use has attribute selector and give the attribute name.

$('[data-my-key]').click...
like image 30
Adil Avatar answered Sep 20 '22 08:09

Adil