Get list of data-* attributes using javascript / jQuery

2020/11/11 00:42 · javascript ·  · 0评论

Given an arbitrary HTML element with zero or more data-* attributes, how can one retrieve a list of key-value pairs for the data.

E.g. given this:

<div id='prod' data-id='10' data-cat='toy' data-cid='42'>blah</div>

I would like to be able to programmatically retrieve this:

{ "id":10, "cat":"toy", "cid":42 }

Using jQuery (v1.4.3), accessing the individual bits of data using $.data() is simple if the keys are known in advance, but it is not obvious how one can do so with arbitrary sets of data.

I'm looking for a 'simple' jQuery solution if one exists, but would not mind a lower level approach otherwise. I had a go at trying to to parse $('#prod').attributes but my lack of javascript-fu is letting me down.


customdata does what I need. However, including a jQuery plugin just for a fraction of its functionality seemed like an overkill.

Eyeballing the source helped me fix my own code (and improved my javascript-fu).

Here's the solution I came up with:

function getDataAttributes(node) {
    var d = {}, 
        re_dataAttr = /^data\-(.+)$/;

    $.each(node.get(0).attributes, function(index, attr) {
        if (re_dataAttr.test(attr.nodeName)) {
            var key = attr.nodeName.match(re_dataAttr)[1];
            d[key] = attr.nodeValue;

    return d;

update 2

As demonstrated in the accepted answer, the solution is trivial with jQuery (>=1.4.4). $('#prod').data() would return the required data dict.

Actually, if you're working with jQuery, as of version 1.4.3 1.4.4 (because of the bug as mentioned in the comments below), data-* attributes are supported through .data():

As of jQuery 1.4.3 HTML 5 data-
attributes will be automatically
pulled in to jQuery's data object.

Note that strings are left intact
while JavaScript values are converted
to their associated value (this
includes booleans, numbers, objects,
arrays, and null). The data-
attributes are pulled in the first
time the data property is accessed and
then are no longer accessed or mutated
(all data values are then stored
internally in jQuery).

The function will return all of the data- attribute inside an object as key-value pairs, with the key being the part of the attribute name after data- and the value being the value of that attribute after being converted following the rules stated above.

I've also created a simple demo if that doesn't convince you:

A pure JavaScript solution ought to be offered as well, as the solution is not difficult:

var a = [], function(at) { return /^data-/.test(; });

This gives an array of attribute objects, which have name and value properties:

if (a.length) {
    var firstAttributeName = a[0].name;
    var firstAttributeValue = a[0].value;

Edit: To take it a step further, you can get a dictionary by iterating the attributes and populating a data object:

var data = {};
[], function(attr) {
    if (/^data-/.test( {
        var camelCaseName =, function ($0, $1) {
            return $1.toUpperCase();
        data[camelCaseName] = attr.value;

You could then access the value of, for example, data-my-value="2" as data.myValue;

Edit: If you wanted to set data attributes on your element programmatically from an object, you could:

Object.keys(data).forEach(function(key) {
    var attrName = "data-" + key.replace(/[A-Z]/g, function($0) {
        return "-" + $0.toLowerCase();
    el.setAttribute(attrName, data[key]);

EDIT: If you are using babel or TypeScript, or coding only for es6 browsers, this is a nice place to use es6 arrow functions, and shorten the code a bit:

var a = [], at => /^data-/.test(;

Have a look here:

If the browser also supports the HTML5 JavaScript API, you should be able to get the data with:

var attributes = element.dataset


var cat =

Oh, but I also read:

Unfortunately, the new dataset property has not yet been implemented in any browser, so in the meantime it’s best to use getAttribute and setAttribute as demonstrated earlier.

It is from May 2010.

If you use jQuery anyway, you might want to have a look at the customdata plugin. I have no experience with it though.

As mentioned above modern browsers have the The HTMLElement.dataset API.
That API gives you a DOMStringMap, and you can retrieve the list of data-* attributes simply doing:

var dataset = el.dataset; // as you asked in the question

you can also retrieve a array with the data- property's key names like

var data = Object.keys(el.dataset);

or map its values by

Object.keys(el.dataset).map(function(key){ return el.dataset[key];});
// or the ES6 way: Object.keys(el.dataset).map(key=>{ return el.dataset[key];});

and like this you can iterate those and use them without the need of filtering between all attributes of the element like we needed to do before.

or convert gilly3's excellent answer to a jQuery method:

$ = function () {
    var data = {};
    [], function (attr) {
        if (/^data-/.test( {
            var camelCaseName =, function ($0, $1) {
                return $1.toUpperCase();
            data[camelCaseName] = attr.value;
    return data;

Using: $('.foo').info();

You should be get the data through the dataset attributes

var data = element.dataset;

dataset is useful tool for get data-attribute

You can just iterate over the data attributes like any other object to get keys and values, here's how to do it with $.each:

    $.each($('#myEl').data(), function(key, value) {

I use nested each - for me this is the easiest solution (Easy to control/change "what you do with the values - in my example output data-attributes as ul-list) (Jquery Code)

var model = $(".model");

var ul = $("<ul>").appendTo("body");

$(model).each(function(index, item) {
  $.each($(this).data(), function(key, value) {
    ul.append($(document.createElement("strong")).text(key + ": " + value));
  }); //inner each
}); // outer each

/*print html*/
var htmlString = $("ul").html();
<script src=""></script>
<link href="" rel="stylesheet"/>
<script src=""></script>
<h1 id="demo"></h1>

  <li class="model" data-price="45$" data-location="Italy" data-id="1234">Model 1</li>
  <li class="model" data-price="75$" data-location="Israel" data-id="4321">Model 2</li> 
  <li class="model" data-price="99$" data-location="France" data-id="1212">Model 3</li> 

<code class="language-html">

<h2>Generate list by code</h2>


One way of finding all data attributes is using element.attributes. Using .attributes, you can loop through all of the element attributes, filtering out the items which include the string "data-".

let element = document.getElementById("element");

function getDataAttributes(element){
    let elementAttributes = {},
        i = 0;

    while(i < element.attributes.length){
            elementAttributes[element.attributes[i].name] = element.attributes[i].value

    return elementAttributes;

文章标签: ,   ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!