2012-01-21

jQuery object index


So always read the manual.



Iterating through a DOMNodeList returned by getElementsByTagName is different from same in jQuery. Even when it returns several elements, the jQuery object is not an array. It is a jQuery object. I had sort of thought of it as an array of multiple jQuery objects - DOMNodeLists, after all, are also not arrays, but their indexes are accessed the same way. Not so with jQuery:

//Vanilla javascript:
var els = document.getElementsByTagName("a");
var str = "";

for (var i = 0; i < els.length; i++) {
 str += "\n" + els[i].getAttribute("href");
}
alert(str);

becomes
//jQuery:
var els = $("a");
var str = "";

for (var i = 0; i < els.length; i++) {
 str += "\n" + els.eq(i).attr("href");
}
alert(str);

In many cases, of course, it is easier to just use .each(), but for various reasons I wasn't able to do that.

No comments:

Post a Comment