Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 871
Luka Krajnc Avatar asked Dec 25 '22 02:12

Luka Krajnc


1 Answers

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>
like image 144
Mohammad Avatar answered Mar 08 '23 14:03

Mohammad