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(...
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(...;
You can use has attribute selector and give the attribute name.
$('[data-my-key]').click...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With