Looping through element's data- attributes

dataset support is very good if you don't need IE below version 11

A simple "for-in" iteration on the dataset property:

var dataset = document.querySelector('div').dataset;

for( var d in dataset)
   console.log(d, dataset[d])
<div data-foo='1' data-bar='2'></div>


In many modern browsers we have access to these special attributes via the .dataset member on the Node object. Unfortunately, this is not yet an accepted standard, and as such we don't see this being adopted all across the spectrum. Fortunately, there is partial support in every major browser in that these attributes can still be accessed using common methods like getAttribute, as well as by cycling over the .attributes list.

The code below shows the second method:

// Reference to our element
var element = document.getElementById("universals"), attr;

// Cycle over each attribute on the element
for (var i = 0; i < element.attributes.length; i++) {
    // Store reference to current attr
    attr = element.attributes[i];
    // If attribute nodeName starts with 'data-'
    if (/^data-/.test(attr.nodeName)) {
        // Log its name (minus the 'data-' part), and its value
        console.log(
            "Key: " + attr.nodeName.replace(/^data-/, ''),
            "Val: " + attr.nodeValue
        );
    }
}

Fiddle: http://jsfiddle.net/pGGqf/14/

You should find that this approach will work in every major browser, even as far back as IE6. This isn't necessary, again, in browsers that support the .dataset member. There's a bit of extra functionality offered on the .dataset object, so you are free to feature-detect it if you like:

if (element.dataset) {
    // Browser supports dataset member
} else {
    // Browser does not support dataset member
}

_dataToObject = function( dataset ) {
    return Object.keys( dataset ).reduce( function( object, key ) {
        object[ key ] = dataset[ key ]; 
        return object;
    }, {});
}

Tags:

Javascript