views:

199

answers:

2

I'm looking for a way to grab the custom attributes of a element with jquery.

<span id='element' data-type='foo' data-sort='bar'></span>

I'm looking to get: ["data-type", "data-sort"] as an array.

Anyone know how to do this?

Thanks.

A: 

just simply $('#element').attr('data-type'); and $('#element').attr('data-sort');

sorry, answered before read the whole question :-/ don't think there's a built in functionality to get them as an array, get the first, get the second and then build the array manually.

robertbasic
+2  A: 

You can use the .attributes DOM property and loop through, like this:

var arr = document.getElementById('element').attributes, attributes = [];
//or if you're inside a jQuery loop, just use this.attributes
//e.g.: var arr = $("span").get(0).attributes, attributes = [];
for(var i = 0; i < arr.length; i++) {
  if(arr[i].name.indexOf("data-") == 0) //only ones starting with data-
    attributes.push(arr[i].name);
}
alert(attributes); ​//use it for something, result is ["data-type", "data-sort"]

You can see a working demo here, aside from grabbing the element, this isn't jQuery specific at all, so you could easily remove it completely if needed.

Nick Craver
Thank you very much. :)
Mark