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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With