Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery get attributes

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.

like image 860
Mark Avatar asked Jun 06 '10 15:06

Mark


1 Answers

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.

like image 90
Nick Craver Avatar answered Sep 28 '22 04:09

Nick Craver