Reputation: 35796
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(...
Upvotes: 29
Views: 40376
Reputation: 148180
You can use has attribute selector and give the attribute name.
$('[data-my-key]').click...
Upvotes: 9
Reputation: 337714
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(...;
Upvotes: 58