Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove div between div using Jquery

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?

like image 325
A Coder Avatar asked Apr 05 '17 10:04

A Coder


2 Answers

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');
like image 193
James Donnelly Avatar answered Oct 17 '22 06:10

James Donnelly


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

like image 39
webknit Avatar answered Oct 17 '22 08:10

webknit