3

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.

3 Answers 3

5

You can call data() to get all data attributes.

Live Demo

myDataArray = $('#myDiv').data();
alert(myDataArray["country"]);
alert(myDataArray["city"]);

You can iterate through key value pair like this,

Live Demo

arr = $('#myDiv').data();

for(el in arr)
{
    alert("Key >> " + el);
    alert("Value >> " + arr[el]);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Is there a selector which would then filter only "data-context-..." attributes or this must be done manually?
Problem is that I do not know that elements will be "country" or "city", they are dynamic... So i need to iterate through array and know both name and value of each element...
Check my updated answer to iterate through collection key, value pair.
5
var myDataObject = document.getElementById('myDiv').dataset;

http://jsfiddle.net/qQWBB/

Comments

1

Try this

var data = $('#myDiv').data();
var myDataArray = [];
$.each(data, function(key, val){
        myDataArray['data-' + key] = val;
});
console.log(myDataArray);

LIVE DEMO

1 Comment

Yes, this also work for me... basically all answers are good on this subject! Many Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.