0

I've few .children element within a .parent div. I would like to loop the children elements.

//This is working good.
$('.parent .children').each(function(){
     //working good.
});

//But I would like to do that in the following way-
var parent = $('.parent');
$(parent + ' .children').each(function(){

});

This time I'm getting the following error-

jquery.min.js:2 Uncaught Error: Syntax error, unrecognized expression: [object Object] .children

Any help?

3
  • 2
    parent.find('.children').each()? Commented Jul 29, 2019 at 11:43
  • 2
    or, $('.children', parent) pass parent element as context which us equivalent to ^^^^ Commented Jul 29, 2019 at 11:44
  • Or you can use $(parent.selector + ' .children').each(function(){}); Commented Jul 29, 2019 at 11:54

2 Answers 2

1

You can use the find() method as follows:

parent.find('.children').each(function() { 
  // Loop here
});

Alternatively, pass parent as the context to the jQuery constructor as follows:

$('.children', parent).each(function() { 
  // Loop here
});
Sign up to request clarification or add additional context in comments.

Comments

1

In above give problem.

//This is working good.
$('.parent .children').each(function(){
     //working good.
});

Above example your are finding children class under parent class.

//But I would like to do that in the following way-
var parent = $('.parent');
$(parent + ' .children').each(function(){

});

In above example you are creating a object of parent class and that's why it is giving issue because wee need to pass string not a object .

Beloved example must help you.

var parent = $('.parent');
    parent.find('.children').each(function(){

    });

Here you are created a object and by use of find we are finding .children class inside a parent class.

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.