29

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(...
1
  • A note on how you're using the selector. Just using the name would select the element. Meaning, the way you had it with just a string, $('div').click would select all DIV elements. $('#div') would select elements with id='div' and $('.div') would select elements with a class='div'. Of course, it would be strange to give an element an ID or Class of div but it's just an example on selection syntax. Commented Dec 14, 2016 at 22:27

2 Answers 2

58

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(...;
Sign up to request clarification or add additional context in comments.

1 Comment

damn!! - i was so close :)
9

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.