Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery loop through HTML5 Data Attributes [duplicate]

Possible Duplicate:
Get list of data-* attributes using javascript / jQuery

I have a series of objects that all look similar to this:

<a data-type="file" data-path="/some/path" data-size="849858">Link</a>

I'd like to create a function to pull each of the data attributes dynamically, so if I add something like "data-icon" or any other number of attributes the function still returns an array of all data attributes like:

{
    "type" : "file",
    "path" : "/some/path",
    ...
}
like image 728
Fluidbyte Avatar asked Sep 03 '12 14:09

Fluidbyte


1 Answers

Edit The initially suggested answer was if you want JSON string / object, which I inferred by the output string you had in the question. If you just want to get the key / value pair you can simply iterate data attribute collection.

Live Demo

$.each($('a').data(), function(i, v) {
    alert('"' + i + '":"' + v + '",');
});

Initially suggested answer on supposition that you want JSON string / object

You can make key value pair object (json object) of data attributes by iterating through data attributes collection using data() which will give the collection of data attributes. After making the json string we can make jSON object using $.parseJSON and using loop to get key / value pair from it.

Live Demo

strJson = "{"
$.each($('a').data(), function(i, v) {
    strJson += '"' + i + '":"' + v + '",';
});
strJson = strJson.substring(0, strJson.length - 1);
strJson += '}';
var jsonObject = $.parseJSON( strJson );
for (var key in jsonObject) 
    alert(key + " : " + jsonObject[key]);
like image 132
Adil Avatar answered Sep 29 '22 21:09

Adil