panthro
panthro

Reputation: 24061

Targeting inside a loop?

$("#questions .question").each(function() {}

.question is an li, inside the .question li is another list with a class .answers, each with an li of class .answer.

I've tried this to target them inside the above loop but no luck:

$(this).$(".answer").each(function() {}

Does anyone know how to target each answer li within the loop using this?

Upvotes: 0

Views: 56

Answers (5)

Atep
Atep

Reputation: 486

Use $(this):

$("#questions .question").each(function() {
    console.log($(this)); // each .question li
}

Upvotes: 0

Kevin Bowersox
Kevin Bowersox

Reputation: 94469

$("#questions .question").each(function() {
    $(this).find(".answer").each( function() {
        //code here
    } );
}

Upvotes: 0

Eldarni
Eldarni

Reputation: 425

$("#questions .question").each(function(index, element) {
    $(element).find('.answer').each(function(index, element) {
        /* do stuff */
    });
});

http://api.jquery.com/jQuery.each/

Upvotes: 0

Richard Dalton
Richard Dalton

Reputation: 35793

You can pass the context to apply the selector to. In this case passing this will achieve what you want:

$("#questions .question").each(function() {
    $(".answer", this).each(function() { // Pass `this` as the context
    });
}

Upvotes: 0

David Hedlund
David Hedlund

Reputation: 129792

$(this).find('.answer') or $('.answer', this)

They are equivalent. From jQuery source:

// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
    return this.constructor( context ).find( selector );
}

Upvotes: 3

Related Questions