Monday, September 07, 2009

Getting all attributes of a DOM element in Javascript/jQuery

Sometimes, you need to iterate over a number of jQuery elements. You pull something like this:

$.each($(".hello"), function() {
alert(this);
});
In this context, the "this" variable is actually not the jQuery objects. According to the 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.

This is helpful when you want all the attributes of a particular DOM element. You can call attributes property on the "this" variable (this.attributes) inside of the each() method to get all attributes of each element with the class hello.

Lastly, if you have a jQuery element, you can get all attributes by:

$("#some_dom")[0].attributes

Posted via web from The Web and all that Jazz

No comments:

Post a Comment