Assume I have a simplified HTML like:
<div id="foobar">
<div id="some-div">...</div>
<div>...</div>
<div id="another-div">...</div>
<div id="keepthis"></div>
.
.
.
</div>
Now I want to remove all elements inside <div id="foobar">
starting from first child until <div id="keepthis">
is reached (which should be kept). In the sample above there are 3 children to remove. In other scenarios it could be 1, 2, 5 or even 0 children.
How can I achieve this with jQuery or JavaScript?
6
Answers
Done. If you have any question feel free to ask.
You can use JQuery’s remove function, then a css :not selector:
Here’s what I did:
Simply:
In pure JavaScript you could use querySelectorAll() with a CSS selector like
*:has(~ #keepthis)
to get the previous all of an element of ID#keepthis
— which uses a combination of the CSS3:has()
selector and the well known subsequent-sibling combinator~
, and remove an Element using theElement.remove()
method.In jQuery it would look like:
:has()
being a CSS3 addition, the syntax method you can use is the supported jQuery’s.prevAll()
making it cleaner and self-explanatory:that jQuery’s
.prevAll()
method could be rewritten in vanilla JavaScript like:Assuming the "until" element (
#keepthis
in your case) might not always exist, and you still want everything (before it) to be removed."Salman A"‘s (great) answer wouldn’t if
#keepthis
element is not found:$("#foobar #keepthis").prevAll().remove();
The below example is highly simplified:
Find the first child and continue until
u
element, and remove everything found:To remove elements coming earlier to the desired div use
.prevAll()
To remove elements coming after the desired div use
.nextAll()
To remove elements coming earlier/after the desired div