views:

50

answers:

1

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 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 ?

Thank you !

A: 

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);
}
Sarfraz
Thanks for the link, But I'm not willing to do this using a plugin. Are there anymore ways ?
Ninja Dude
Why wouldn't you want to use a plugin? At the very least, open the plugin and see how they did it.
Soviut
@Avinash: See my updated answer please.
Sarfraz
@Avinash: I would still suggest you to use the plugin, note also that it is only 490 bytes.
Sarfraz
@Sarfraz Thanks for the updated Answer !!
Ninja Dude
@Avinash: You are welcome...
Sarfraz
It seems odd that you don't want to use a plugin. Plugins are just jquery code. You could just look at the plugin source and see how they do it.
Gregg
Ninja Dude