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?
Here, the area of DIV element is shown by the red border, and we can clearly see that text is going beyond it. We can solve this problem by using CSS overflow property. overflow: hidden; hidden – The overflow is clipped, and the rest of the content will be invisible.
Removing an element using the removeChild() method First, select the target element that you want to remove using DOM methods such as querySelector() . Then, select the parent element of the target element and use the removeChild() method.
You can use :not()
or not()
to avoid the element inside #container
$('.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>
Using not()
$('.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>
//$('.baby:not(#container .baby)').remove();//select class baby not inside container using selector :not
$('.baby').not('#container .baby').remove();//select class baby not inside container using method .not()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div class="baby">1</div>
<div class="baby">2</div>
<div class="baby">3</div>
<div class="baby">4</div>
</div>
<div id="someID">
<div class="baby">5</div>
<div class="baby">6</div>
<div class="baby">7</div>
</div>
<div class="baby">8</div>
<div class="baby">9</div>
<div class="baby">0</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With