[英]How to select all previous siblings of element using jquery?
Let's say I have a div with next content: 假设我有下一个内容的div:
<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. 我只想在
id="aggregatedDiv"
之前删除所有内容,包括它。
I have to append the result as html to some other div. 我必须将结果作为html附加到其他div。
$("#otherDiv").append(resultOfSlicedDivOneHtml);
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. 您可以使用
.prevAll()
来选择元素的所有先前兄弟,并使用.addBack()
将前一个选择器( #aggregatedDiv
)添加到当前所选元素集。
$("#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>
如上所述,你可以使用.prevAll()
,但你也需要.addBack()
来实现你想要的:
$("#otherDiv").append($("#aggregatedDiv").prevAll().addBack());
This should work: 这应该工作:
var elements = $("#aggregatedDiv").prevAll(); //gets everything before aggregatedDiv
elements = elements.add($("#aggregatedDiv")); //we want aggregatedDiv in the collection as well
$("#otherDiv").append(elements); //move them all into the other div
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.