views:

76

answers:

4

I realize the code below is not the most efficient way of grabbing elements, but for the sake of an example...

$('.myFirstClass').each(function(i){
   // Here is the first 'THIS' occurrence
   $(this).find('.mySecondClass').each(function(j){
      // Here is the second 'THIS' occurrence
      // How do i access the first occurrence from here?
   });
});
+3  A: 

Store the this in a var before the inner each.

$('.myFirstClass').each(function(i){
   //store this
   var $that = $(this);
   $(this).find('.mySecondClass').each(function(j){
      //$that.something
      // How do i access the first occurrence from here?
   });
});
redsquare
+4  A: 

Something like this,

$('.myFirstClass').each(function(i){
   var firstClassThis = this;
   $(this).find('.mySecondClass').each(function(j){
      // Here is the second 'THIS' occurrence
      // How do i access the first occurrence from here?
      //You can use firstClassThis here due to closure. 
   });
});
SolutionYogi
`var firstClassThis = this;` is redundant. jQuery already manages these identifiers. See my answer.
Jonathan Sampson
If you are already using index, your code looks better. If I didn't care for the index, I would probably capture 'this' in a local variable.
SolutionYogi
True. +1
Jonathan Sampson
+4  A: 

No need to store variables. jQuery already does this in the second parameter...

$(".myFirstClass").each(function(i, j){
  // I am represented as this or j
  $(j).find(".mySecondClass").each(function(a, b){
    // I am represented as this or b
    // I can communicate with j
  });
});
Jonathan Sampson
yeah, personally I do not like the params everywhere. Much cleaner using the var imo.
redsquare
+1  A: 
$('.myFirstClass').each(function(i){
   var me = this;
   $(this).find('.mySecondClass').each(function(j){
      alert($(me).attr('id'));
   });
});

That should work.

inkedmn
You should specify the 'var' keyword for the 'me' variable.
SolutionYogi