jQuery loop through HTML5 Data Attributes
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.
$.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.
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]);
Fluidbyte
I am an architect/engineer from Wisconsin working primarily in the JavaScript/NodeJS ecosystem with a passion for process/task automation, CI, and Docker.
Updated on June 09, 2022Comments
-
Fluidbyte about 2 years
Possible Duplicate:
Get list of data-* attributes using javascript / jQueryI 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", ... }
-
gilly3 over 8 yearsThis is such a bad answer. You already have the object:
$("a").data()
. But you are cloning that object, which by itself is pointless, but you are doing it by creating JSON via string concatenation! So many better ways to clone an object! You then parse the JSON back to an object (which you already had), and then loop through that object (which you already did). -
Adil over 8 yearsThanks gilly, I inferred from the output that he wants JSON string / object, I totally agree for key pair it should not be converted to JSON and now I think he does not want JSON.
-
Gino almost 7 yearsWith json i get this error "Uncaught SyntaxError: Unexpected token } in JSON at position 0"
-
Gino almost 7 yearsOk, i find out if there's no data- in it it make this error. We can check if data with: $.hasData('a')
-
Aryo about 3 yearsIf you use an data-attribute key with dash on it, it will be recognized in camel case key. For example:
data-sample-key="123"
, the key will be recognized assampleKey
, notsample-key
.