Nick
Nick

Reputation: 2549

jQuery - Remove all child elements before specific child

JSFiddle: https://jsfiddle.net/9krvkfpw/

Hi,

I'm trying to remove all child elements up to a certain point but I'm not too sure what the most effective way to do this is.

Here's some example code:

<div id="container">
    <div id="el1">Remove</div>
    <div id="el2">Remove</div>
    <div id="el3">Remove</div>
    <div id="el4">Remove</div>
    <script type="text/javascript">
    // Keep
    </script>
    <div id="lastEl">Keep</div>
</div>

Essentially, what I want to do is remove all elements above the script element. I can't just find the first script element because sometimes there's more above the one I want to keep, so they'll get in the way.

My idea was to get the script tag by hitting the #lastEl and getting the previous element.

Like this:

var script = $('#container').children('#lastEl').prev();

From here I'm not sure what the best way to proceed is, or if this is even the best way?

I could do something like script.prev().remove() multiple times, but this isn't always going to work because there's always a different number of elements previous to the script I'm starting with.

Any ideas would be great!

Thanks!

Upvotes: 3

Views: 1680

Answers (3)

eisbehr
eisbehr

Reputation: 12452

prevAll is what you are looking for:

$("#lastEl").prevAll("div").remove();

Upvotes: 0

George G
George G

Reputation: 7695

To answer what you are looking for exactly:

Essentially, what I want to do is remove all elements above the script element

You can do following:

$('#container script').prevAll().remove();

Fiddle

Upvotes: 4

guradio
guradio

Reputation: 15555

$('#container').find('#lastEl').prev().prevAll().remove()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
    <div id="el1">Remove</div>
    <div id="el2">Remove</div>
    <div id="el3">Remove</div>
    <div id="el4">Remove</div>
    <script type="text/javascript">
    // Keep
    </script>
    <div id="lastEl">Keep</div>
</div>

Try this approach

Upvotes: 0

Related Questions