Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Targeting $(this) within nested for each loops in jQuery

I'm trying to figure out, when iterating through some list items, how to target each "$(this)" equivalent within nested foreach loops. Here is an example of my problem:

$('li').each(function(){
        // I believe $(this) would target each li item...
    $(this).children("li").each(function(){
        // ... but how can I target each of these li items? Doesn't $(this) target the original loop?
    });
});
like image 687
mmmoustache Avatar asked May 02 '13 19:05

mmmoustache


5 Answers

$('li').each(function(){
    var $this = $(this);
    $this.children("li").each(function(){
        $this; // parent li
        this; // child li
    });
});
like image 184
Gabe Avatar answered Nov 16 '22 08:11

Gabe


Don't use this! Use function parameters!

$('li').each(function(i, li){
    $(li).children("li").each(function(ii, li2){
        $(li)...
        $(li2)...
    });
});

This is more in keeping with the native JavaScript iterators.

...though an <li> can't be the direct child of another <li>

like image 26
user1106925 Avatar answered Nov 16 '22 08:11

user1106925


Look at the basic "prototypes" of jQuery functions (or methods, if you will):

$[jQobject].[func]([callback]);

The callback is the function that will be invoked in the context of the jQ object. The context being this, obviously. Put simply that means that:

$('#foo').click(function(){});
   /\                 /\
   || Is the context  ||
   =====================

The same applies to your case, regardless of the loops being nested or not:

$('ul').each(function()
{
    //this is ul
    var that = this;//you'll often see code like this
    $('li', this).each(function()
    {
        //this is li
        //that is parent ul
    });
});
like image 10
Elias Van Ootegem Avatar answered Nov 16 '22 07:11

Elias Van Ootegem


but how can I target each of these li items? Doesn't $(this) target the original loop?

Nope.

this comes from the function you're directly in.

like image 3
SLaks Avatar answered Nov 16 '22 09:11

SLaks


Nope, this refers to each of the child <li> items. Try it out.

Most (if not all) DOM-interacting jQuery callbacks set this to to the DOM element that you're working with.

You could also write:

$('li').children("li").each(function(){
    var $this = $(this);
});
like image 2
Blender Avatar answered Nov 16 '22 07:11

Blender