根据其同级元素包裹元素



如果p元素位于.image类之前或之后,我将尝试将它们封装在单个div中。目前,我只能围绕每一个单独的元素。

这是我的CSS:

<ul>
    <p>this is the first paragraph</p>
    <p>this is the second paragraph</p>
    <div class="image"></div>
    <div class="image"></div>
    <p>this is the third paragraph</p>
    <p>this is the fourth paragraph</p>
</ul>

和我的jQuery:

$('p').wrap('<div class="new" />');
$('.image').wrap('<li />');

这是我的JSFIDDLE:http://jsfiddle.net/BDqGe/

有人知道如何根据其兄弟来包装元素吗?

您的HTML首先是无效的,因为如果您在这里查看

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul

ul-零个或多个<li>元素的允许含量,最终与<ol><ul>元素混合。

但是,您可以通过使用prevAll()来获取之前的所有同级,使用.nextAll()获取元素之后的所有同级来包装所有元素,然后.wrapaAll()将使用单个元素来包装它们

$('.image') // start at .image
       .prevAll('p') // <-- get all p's before .image
       .wrapAll('<div class="new" />') // wrap all in a div
       .end() // go back to .image
       .nextAll('p') // get all p's after .image
       .wrapAll('<div class="new" />') // wrap all in div
       .end() // go back to .image
       .wrap('<li />'); // wrap .image in li

FIDDLE

我的方法将是

var $ul = $('ul');
$ul.find('.image').wrap('<li />');
$ul.children('p').filter(function(){
    var $prev = $(this).prev();
    return $prev.length == 0 || $(this).prev().is(':not(p)')
}).each(function(){
    $(this).nextUntil(':not(p)').addBack().wrapAll('<li class="new"/>')
})

演示:Fiddle

最新更新