Wednesday, December 23, 2009

Re: [jQuery] Re: how to access elements with index in for-loop

thank you very much, your way is better than mine !

2009/12/24 Šime Vidas <sime.vidas@gmail.com>

First of all, the "wrong" code is wrong, look.... this is your code:

$(function(){
       var trs = $("#tb tr:not(:first)")

       for( var i=0; i<$trs.length; i++ ) {
               //$trs[i].find("td:eq(1)").attr("style","color:red");   //wrong
               $trs.get(i).find("td:eq(1)").attr("style","color:red"); //wrong
       }
})


1. you forgot to put semicolons at two places.....

$(function(){
       var trs = $("#tb tr:not(:first)"); <-- HERE

       for( var i=0; i<$trs.length; i++ ) {
               //$trs[i].find("td:eq(1)").attr("style","color:red");   //wrong
               $trs.get(i).find("td:eq(1)").attr("style","color:red"); //wrong
       }
}); <-- HERE

2. You declared a variable named "trs" but you than use a varibale
named "$trs" which of course doesn't exist because you haven't
declared it...

$(function(){
       var $trs = $("#tb tr:not(:first)");

       for( var i=0; i<$trs.length; i++ ) {
               //$trs[i].find("td:eq(1)").attr("style","color:red");   //wrong
               $trs.get(i).find("td:eq(1)").attr("style","color:red"); //wrong
       }
});

OK, now the code should work, right?

Well, no... because what the get(i) method does is it returns the DOM
element at index i from the $trs jQuery obect.... so after you do get
(i), you no longer have an jQuery object, and you cannot call the find
() method because it is not a property of DOM elements....

What you could do is encapsulate $trs.get(i) inside $() to get a
jQuery object based on the DOM element, so this code does work:

$($trs.get(i)).find("td:eq(1)").attr("style", "color:red");


However, this is a pretty stupid way to loop through a jQuery
object... a better way is to use the each() method:

$trs.each(function() {
       $(this).find("td:eq(1)").attr("style", "color:blue");
});


No comments: