48

Similar to this question here, I'm looking to get an element based on it's data-id.

<a href="#" class="whatever" data-item-id="stand-out">...</a>

I'm looking to take action on the a tag. It has a shared class amongst many other elements and has no base id, just a data-item-id.

Can the element be found by it's data-item-id or can I only find out what the data-item-id is?

Community
  • 1
  • 1
MacSalty
  • 1,162
  • 4
  • 13
  • 21
  • 1
    possible duplicate of [Select elements by HTML5 data attribute in jQuery](http://stackoverflow.com/questions/4993447/select-elements-by-html5-data-attribute-in-jquery) – Kevin B Nov 08 '13 at 18:57
  • 1
    For those that arrived here via Google. Note that the answers here reflect how to get an element by data-item-id and not data-id. – Gabe Jun 05 '19 at 14:12

4 Answers4

76

$('[data-item-id="stand-out"]')

kumarharsh
  • 18,026
  • 7
  • 71
  • 97
56

You can always use an attribute selector. The selector itself would look something like:

a[data-item-id=stand-out]
Justin Niessner
  • 236,029
  • 38
  • 403
  • 530
  • 1
    Double quotes around (in this case) stand-out are required as per kd12's answer. Note also that this expression will search every a element on the page. If you want to optimize it, you can limit the search using a parent element id or a class. – Henrik Erlandsson Jan 09 '20 at 09:51
22

This worked for me, in my case I had a button with a data-id attribute:

$("a").data("item-id");

Fiddle

Studocwho
  • 2,336
  • 3
  • 21
  • 27
Trevor
  • 1,491
  • 1
  • 19
  • 26
21

Yes, you can find out element by data attribute.

element = $('a[data-item-id="stand-out"]');
kd12
  • 1,281
  • 1
  • 13
  • 22