[英]How to wrap all elements inside a div after a certain element? (JQuery)
I have an article tag that has elements inside it. 我有一个文章标签,里面有元素。
Problem: How can I wrap all elements inside a div after a certain element? 问题:如何在某个元素之后将div中的所有元素包装起来?
This is the current code: 这是当前的代码:
<article>
<figure class="thumbnail">
<img src="src_to_img" />
</figure>
<h2>Name: Test Name</h2>
<div class="description"></div>
<div class="content"></div>
<div class="content"></div>
<div class="more"></div>
<article>
The output must be: 输出必须是:
<article>
<figure class="thumbnail">
<img src="src_to_img" />
</figure>
<div class="description-wrap">
<h2>Name: Test Name</h2>
<div class="description"></div>
<div class="content"></div>
<div class="content"></div>
<div class="more"></div>
</div>
<article>
As you can see.. the final output has all the elements wrapped inside class="description-wrap"
after <figure></figure>
正如你所看到的......最终输出的所有元素都包含在
<figure></figure>
之后的class="description-wrap"
As @squint suggested, jQuery has a wrapAll method that can do that if combined with the next-siblings-selector ~
正如@squint建议的那样,jQuery有一个wrapAll方法,如果与下一个siblings-selector结合使用可以做到这一点
~
$("article > figure ~ *").wrapAll("<div class='description-wrap'></div>")
however, this doesn't give you the desired output when you have multiple articles. 但是,当您有多篇文章时,这并不能为您提供所需的输出。 Instead we need to use
.each()
like so: 相反,我们需要像这样使用
.each()
:
$("article > figure").each(function(){ $(this).siblings().wrapAll("<div class='description-wrap'></div>") });
.description-wrap {border:1px dotted red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <article> <figure class="thumbnail"> <img src="src_to_img" /> </figure> <h2>Name: Test Name</h2> <div class="description"></div> <div class="content"></div> <div class="content"></div> <div class="more"></div> </article> <article> <figure class="thumbnail"> <img src="src_to_img" /> </figure> <h2>Name: Test Name</h2> <div class="description"></div> <div class="content"></div> <div class="content"></div> <div class="more"></div> </article>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.