jquery get all elements matching data attribute name

38,138

Solution 1

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(...;

Solution 2

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

$('[data-my-key]').click...
Share:
38,138
Marty Wallace
Author by

Marty Wallace

Updated on November 20, 2020

Comments

  • Marty Wallace
    Marty Wallace over 3 years

    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(...