0

When I create loop inside a loop and want to access this element inside the second loop, I referenced to this link(Targeting $(this) within nested for each loops in jQuery). I use

var $this = $(this);

Where $this references first loop and $(this) references second. But I need one more inside the second loop and need to access another "this" object of third loop. I need to have something like this

  $('.section1').each(function(){
       var $this = $(this);
          $this.find('div[class = "text_question"]').each(function(){
                   $(this).find('label').each(function() {
                            //I want to access the element of this loop (each label object's text)
                });
}

How can I achieve that?

2 Answers2

0

To make it cleaner, you can define parameters for the callbacks:

$('.section1').each( function(index, sectionItem) {
    sectionItem.find('div[class = "text_question"]').each( function(index, questionItem) {
        questionItem.find('label').each( function(index, labelItem) {
            // use labelItem here
        });
    });
});

You can also find more info here: https://api.jquery.com/jquery.each/

Also, as Justinas pointed out, you can get the label elements with one selector:

$('.section1 .text_question label').each( function(index, labelItem) {
    // use labelItem here
});

Hope this helps.

Romi Halasz
  • 1,949
  • 1
  • 13
  • 23
0

You can assign $(this) to a variable of any name. So in your 2nd loops you can add var this2 = $(this), or any name you prefer. You can access it by calling the variable directly like this2.find(...

Shreyas Sreenivas
  • 331
  • 1
  • 5
  • 12