0

I have some divs that i use as containers, i want to loop over them and then loop over the items in it.

so not $('.stackContainer .stackItem').each( but something like this:

// setup stacks
$('.stackContainer').each(function(containerIndex) {
    //console.log($(this));
    console.log(containerIndex);

    $(this).('.stackItem').each(function(itemIndex) {
        console.log(itemIndex);     
    }
});

Only then working. How is this possible?

1
  • Open your browser's developer console and you will know why your code is wrong. Commented Jun 10, 2012 at 12:23

4 Answers 4

2

Try

$('.stackContainer').each(function(containerIndex) {
    //console.log($(this));
    console.log(containerIndex);

    $(this).find('.stackItem').each(function(itemIndex) {
        console.log(itemIndex);     
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

try find() method:

$('.stackContainer').each(function(containerIndex) {
    //console.log($(this));
    console.log(containerIndex);

    $(this).find('.stackItem').each(function(itemIndex) {
        console.log(itemIndex);     
    }
});

Comments

0

Many ways of doing this, as other answers have indicated. Here's one solution: http://jsfiddle.net/cezHH/3/

$(".stackContainer").each(function(stackIndex) {
    $(this).children().css('class', '.stackItem').each(function(itemIndex) {
        $(this).html($(this).html() + "=>" + itemIndex);
    });
});​

Alternatively, if all you want to do is iterate over all the .stackItem divs in the order in which they appear on the page, and you don't actually care about the parent .stackContainer divs, then you could just do $('.stackItem').each(function(index) { ... });

The reason to nest the loop that iterates over the .stackItem divs is if you want the itemIndex variable to reset to zero each time you switch parent containers.

Comments

0

On a side note, for performance reasons, you should avoid using jQuery's each() if it's possible that the collection will be of any size:

http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/

http://jsperf.com/jquery-each-vs-for-loop

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.