Luka Krajnc Luka Krajnc - 3 months ago 9
HTML Question

How to select all previous siblings of element using jquery?

Let's say I have a div with next content:

<div id="divOne">
<p>one</p>
<p>two</p>
<div id="aggregatedDiv"></div>
<p> three </p>
</div>


So is there any way to remove first three elements? I don't know the number of elements. I just want to remove everything before
id="aggregatedDiv"
including it.

I have to append the result as html to some other div.

$("#otherDiv").append(resultOfSlicedDivOneHtml);

Answer

You can use .prevAll() to selecting all previous sibling of element and use .addBack() to adding previous selector (#aggregatedDiv) to current set of selected element.

$("#aggregatedDiv").prevAll().addBack().css("color", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divOne">
    <p>one</p>
    <p>two</p>
    <div id="aggregatedDiv">#</div>
    <p> three </p>
</div>

If you want to add selected element to another element, use bottom example:

$("#aggregatedDiv").prevAll().addBack().appendTo("#divTwo");
#divTwo {color: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divOne">
    <p>one</p>
    <p>two</p>
    <div id="aggregatedDiv">#</div>
    <p> three </p>
</div>
<div id="divTwo"></div>