Reputation: 5144
I have an element I need to get an array of specific attributes. For example:
<div id="myDiv" class="myClass" data-country="US" data-city="NY" />
In this example, I need to get all data-*
attributes and place them in array (name and value pairs).
In this example, final array would look like this:
myDataArray["data-country"] = "US";
myDataArray["data-city"] = "NY";
Problem is that these attributes are dynamic, I do not know what attributes will be there at the runtime and I cannot hard code filling of array.
Upvotes: 3
Views: 5216
Reputation: 2150
Try this
var data = $('#myDiv').data();
var myDataArray = [];
$.each(data, function(key, val){
myDataArray['data-' + key] = val;
});
console.log(myDataArray);
Upvotes: 1
Reputation: 148110
You can call data() to get all data attributes.
myDataArray = $('#myDiv').data();
alert(myDataArray["country"]);
alert(myDataArray["city"]);
You can iterate through key value pair like this,
arr = $('#myDiv').data();
for(el in arr)
{
alert("Key >> " + el);
alert("Value >> " + arr[el]);
}
Upvotes: 5