JQuery get multiple attributes
I have an element that 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 the attributes data-*
and put them in an array (name and value pairs).
In this example, the resulting array will look like this:
myDataArray["data-country"] = "US";
myDataArray["data-city"] = "NY";
The problem is that these attributes are dynamic, I don't know what attributes will be present at runtime and I cannot hard-code the filling of the array.
+3
source to share
3 answers
You can call data () to get all the data attributes.
myDataArray = $('#myDiv').data();
alert(myDataArray["country"]);
alert(myDataArray["city"]);
You can iterate through a key value pair like this,
arr = $('#myDiv').data();
for(el in arr)
{
alert("Key >> " + el);
alert("Value >> " + arr[el]);
}
+5
source to share