I need to remove div
elements which are loaded dynamically between two static div
elements.
HTML
<div id="defaultFirst">
</div>
..
..
..
<div id="defaultLast">
</div>
There are some div
elements which are loaded in between those two static div
elements. Now I need to remove those before I append some other elements.
I tried using $('#defaultFirst').nextAll('div').remove()
but that removed the #defaultLast
element too.
I know that I can get the ids of the dynamic div
and remove. But I need to know if there is any simpler way to remove those dynamic div
elements?
Use nextUntil()
instead of nextAll()
and pass in a selector which selects your #defaultLast
element:
$('#defaultFirst').nextUntil('#defaultLast').remove();
.nextUntil( [selector ] [, filter ] )
Description: Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed.
— jQuery's documentation on
nextUntil()
If you have elements which aren't div
elements between those two which you aren't wanting to remove, you can specifically remove only div
elements by passing in a selector to your remove()
call:
$('#defaultFirst').nextUntil('#defaultLast').remove('div');
I would recommend getting to the cause of why the divs are appearing in the first place rather than hacking like this. However if you have to then the following should work
$('#defaultFirst').nextAll('div').not('#defaultLast').remove();
Codepen example - http://codepen.io/webknit/pen/ZeZXdQ
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