Evanss
Evanss

Reputation: 23593

jQuery wrapAll children if they dont already have a parent with certain class

Im using the following to wrap all items with a class of 'child' with a div with a class of 'parent':

$(".child").wrapAll('<div class="parent" />');

The issue is that the function is sometimes rerun and I dont want multiple div.parents' to be created. How can I add a condition to my code so the div.parent is only added if div.childs' dont already have a parent with a class of 'parent'? Thanks

Upvotes: 0

Views: 287

Answers (3)

Vasily Komarov
Vasily Komarov

Reputation: 1415

Your can do it in single row )

$(".child").parents('p:not(.parent)').find(".child").wrapAll('');

Upvotes: 0

Vytautas
Vytautas

Reputation: 3539

Don't know is it fast:

$(":not(.parent) > .child").wrapAll('<div class="parent" />');

not tested!! but may work

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382746

You can use hasClass() like this:

if (! $(".child").parent().hasClass('parent')){
   $(".child").wrapAll('<div class="parent" />');
}

Or using closest with length:

if (! $(".child").closest('.parent').length){
   $(".child").wrapAll('<div class="parent" />');
}

Upvotes: 1

Related Questions