following is my HTML
HTML :
<div Attr1 = "val1" Attr2 = "val2" Attr3 = "val3" >
Hello !!
</div>
I want to extract all the attributes (& its corresponding values
) of an element.
How can I do this using jQuery?
I tried something like开发者_StackOverflow below,
$(function() {
for(var i in $('div')[0].attributes) {
console.log($('div')[0].attributes)[i] , $('div')[0].attributes)[i].value);
}
});
Are there any more possible ways for doing this ?
You are looking for getAttributes jQuery Plugin.
A simple and small (490 bytes minified) plugin to retrieve all attributes from an element (useful if you have to work with markup that you don't have control over). It returns an object that can be used as the argument to .attr()
Example:
console.log($.getAttributes('div'), true);
Update:
From jQuery Docs:
Whenever you use jQuery's each-method, the context of your callback is set to a DOM element. That is also the case for event handlers.
Meaning you can do:
var attrs = $("div")[0].attributes;
for(var i = 0; i < attrs.length; i++) {
alert(attrs[i].nodeName + " => " + attrs[i].nodeValue);
}
精彩评论