Instead of using the regular attr() is there a shorthand in jQuery to access all the data-*
attributs of an element. One which enable me to just specify the name without the data-
prefix, like dataset
document.getElementById('id').dataset.somename;
Asked
Active
Viewed 1,742 times
0

Itay Moav -Malimovka
- 52,579
- 61
- 190
- 278
-
yes, you can use https://api.jquery.com/jquery.data/ or https://api.jquery.com/data/ – CrayonViolent Aug 04 '15 at 17:14
-
not entirely sure what you mean..this is something baked into jQuery. For example if you have `foo` you can do e.g. `$('a#foobar').on('click',function() { console.log($(this).data('foo'); });` – CrayonViolent Aug 04 '15 at 17:19
-
Possible duplicate of http://stackoverflow.com/questions/23592030/get-data-attribute – zed Aug 04 '15 at 17:47
1 Answers
1
Answer: Yes. There is a shorthand to get all the data-* attributes from an element.
To grab a single element's data value (which looked like what you wanted, but I guess it's not..?):
$("div").data("name");
That would grab the value from data-name
. Example:
<div data-name="Jacob"></div>
$("div").data("name"); //"Jacob"
To grab all the data-* attributes, you can do this:
$("div").data();
Here's an example for what you can do: http://jsfiddle.net/nhzj3qtk/1/

MortenMoulder
- 6,138
- 11
- 60
- 116
-
Please read the question, he is not asking HOW to get the data attribute. He wants to know how to list ALL data attributes. – Martin at Mennt Aug 04 '15 at 17:24
-
Maybe so, but I think `"... is there a shorthand in jQuery to access all the data-* attributs of an element"` is pretty clear. – Martin at Mennt Aug 04 '15 at 17:32
-
1@Martin well his followup sentence sounds like he more specifically wants to grab a specific value, and his example at the very end seems to confirm that. So my overall takeaway is that his initial "access all the data-\*.." was meant more like "access data-\*..". IOW more "access this stuff in general". My 2 cents – CrayonViolent Aug 04 '15 at 17:34
-
@CrayonViolent That was my initial thought as well. After rereading it, I read it as multiple attributes, but still fall back to what I answered with. – MortenMoulder Aug 04 '15 at 17:35
-
in any case, if OP really wants *all* attributes, calling `.data()` without any parameters will return an object with all `data-*` attributes – CrayonViolent Aug 04 '15 at 17:41
-
@Snorlax, after your update it's unclear to me if the answer is "no" (as stated) or the answer is "yes"... – zed Aug 04 '15 at 17:57
-