Ø  this is a pretty stupid way to loop through a jQuery
object

 

Is it necessary to be insulting to be helpful, Eric?  What was your

code like when you first began to write JS or jQuery?  Always

perfect and mature, I’m sure…

 

Rick

 

From: jquery-en@googlegroups.com [mailto:jquery...@googlegroups.com] On Behalf 
Of Eric Zhong
Sent: Wednesday, December 23, 2009 9:52 PM
To: jquery-en@googlegroups.com
Subject: 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.vi...@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");
});

 

Reply via email to