skyguy skyguy - 2 months ago 6
CSS Question

JQuery select and remove all ps that are not in a certain div?

Ok, I have a pretty complicated html setup here, and in my function I need to remove all the ps (NOT just all divs, ps specifically) that are NOT within these 2 subclasses :

.panel-heading
and
.panel-body


Originally I got all ps in the following:

<div class="panel panel-default">

<div class="panel-heading" role="tab" id="headingEight">

<h4 class="panel-title"><a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseNine2" aria-expanded="false" aria-controls="collapseNine2"><i class="fa fa-plus-square-o"></i> <span style="margin-left: 12px; display: inline-block;"></span>AirWatch and Workspace ONE</a>

</h4>

</div>

<div id="collapseNine2" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingEight">

<div class="panel-body">


with this:

$(labArr[i].selector).find(".panel-default").find("p").remove()


And this works except its deleting literally all the ps, which I can't have. I know I need to use the not selector so Ive tried:

$(labArr[i].selector).find(".panel-default").find("div:not(.panel-body, .panel-heading)").remove();


and

$(labArr[i].selector).find(".panel-default:not(.panel-body, .panel-heading)").find("p").remove();


which did not work. I don't know why.

How can I remove ALL ps in panel-default except the ones in those 2 classes?

Answer

As always with selectors, there's lots of different ways to achieve the same thing, but try this:

$(labArr[i].selector).find(".panel-default p").not(function() {
    return $(this).closest('.panel-body, .panel-heading').length;
}).remove();

That inspects each paragraph matched, then discards any that live under an element with the two prohibited classes.