Remove div from div using jQuery

I need to remove div elements that are dynamically loaded between two static div elements.

HTML

 <div id="defaultFirst"> </div> .. .. .. <div id="defaultLast"> </div> 

There are several div elements that are loaded between these two static div elements. Now I need to remove them before adding some other elements.

I tried using $('#defaultFirst').nextAll('div').remove() but also removed the #defaultLast element.

I know I can get the dynamic div ids and delete. But I need to know if there is an easier way to remove these dynamic div elements?

+5
source share
2 answers

Use nextUntil() instead of nextAll() and pass in the selector that your #defaultLast element #defaultLast :

 $('#defaultFirst').nextUntil('#defaultLast').remove(); 

.nextUntil( [selector ] [, filter ] )

Description: Get all of the following siblings of each element, but not including the element corresponding to the selector, DOM node, or jQuery object passed.

- jQuery documentation on nextUntil()

If you have elements that are not div elements between the two that you do not want to remove, you can specifically remove only div tags by passing a selector to your remove() call:

 $('#defaultFirst').nextUntil('#defaultLast').remove('div'); 
+11
source

I would recommend understanding the reason divs appear first and not hack like this. However, if you need to, then the following should work

 $('#defaultFirst').nextAll('div').not('#defaultLast').remove(); 

Codepen example - http://codepen.io/webknit/pen/ZeZXdQ

+5
source

Source: https://habr.com/ru/post/1266354/


All Articles