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;
1 Answer
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/
7 Comments
Martin at Mennt
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
Maybe so, but I think
"... is there a shorthand in jQuery to access all the data-* attributs of an element" is pretty clear.CrayonViolent
@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
MortenMoulder
@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.
CrayonViolent
in any case, if OP really wants all attributes, calling
.data() without any parameters will return an object with all data-* attributes |
<a id='foobar' data-foo='bar' href='..'>foo</a>you can do e.g.$('a#foobar').on('click',function() { console.log($(this).data('foo'); });