Skip to content Skip to sidebar Skip to footer

Looping Through Element's Data- Attributes

Per, How to iterate through all attributes in an HTML element? you get the general solution: for (var i = 0; i < elem.attributes.length; i++) { var attrib = elem.attributes[i]

Solution 1:

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>

Solution 2:

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
}

Solution 3:

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

Solution 4:

If you don't want to use regex you could try

if attrib.name.startswith('data'):
    //do something

Solution 5:

I have a concept here that may work for you.

var el = document.getElementById("universals");
for(var i=0;i<el.attributes.length;i++){
    if((el.attributes[i].nodeName+"").indexOf("data-")>-1){
        var key=(el.attributes[i].nodeName+"").substring(5);
        var value=el.attributes[i].value;
        alert(key+": "+value);
    }
}

This is the basic idea I have come up with that seems to work pretty well. I have also created function which returns the a Name-Value-Pair object out of an HTMLElements "data" attributes using this method above.

function data2Obj(id){
  var obj={};
  var el=document.getElementById(id);
  for(var i=0;i<el.attributes.length;i++){
    if((el.attributes[i].nodeName+"").indexOf("data-")>-1){
      var key=(el.attributes[i].nodeName+"").substring(5);
      var value=el.attributes[i].value;
      if(value.toLowerCase()=="true")value=true;
      else if(value.toLowerCase()=="false")value=false;
      else if((parseInt(value)+"")==value)value=parseInt(value);
      obj[key]=value;
    }
  }
  return obj;
}

This can easily be modified to accept a class or any other method for selecting HTMLElements.

If you take the return of this function and iterate through the object you should get your desired result.

var datas = data2Obj("universal");
for(var k in datas){
  alert(k+": "+datas[k]);
}

Post a Comment for "Looping Through Element's Data- Attributes"