Jackson Jackson - 7 months ago 10
Javascript Question

Remove all the elements outside of a container?

I'm trying to find a way to remove all the elements (div's) outside of a specific container.

For example:

I have an HTML container with a few div's inside of it like so:

<div id="container">
<div class="baby"></div>
<div class="baby"></div>
<div class="baby"></div>
<div class="baby"></div>
</div>
<div id="someID">
<div class="baby"></div>
<div class="baby"></div>
<div class="baby"></div>
</div>
<div class="baby"></div>
<div class="baby"></div>
<div class="baby"></div>


I basically need to remove all the elements with the class name
baby
that is outside of
container
. Some of the elements don't even have a container so I cannot target them using the parent or anything like that.

Is this possible at all?

Answer

You can use :not() or not() to avoid the element inside #container

$('.baby:not(#container .baby)').remove();
// or
// $('.baby').not('#container .baby').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
  <div class="baby">1</div>
  <div class="baby">1</div>
  <div class="baby">1</div>
  <div class="baby">1</div>
</div>
<div id="someID">
  <div class="baby">2</div>
  <div class="baby">2</div>
  <div class="baby">2</div>
</div>
<div class="baby">3</div>
<div class="baby">3</div>
<div class="baby">3</div>

Comments