51

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,212
  • 4
  • 14
  • 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

83

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

kumarharsh
  • 18,961
  • 8
  • 72
  • 100
61

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

a[data-item-id=stand-out]
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • 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
25

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

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

Fiddle

Studocwho
  • 2,404
  • 3
  • 23
  • 29
Trevor
  • 1,561
  • 1
  • 20
  • 28
21

Yes, you can find out element by data attribute.

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