是否可以全选<p>
彼此相邻的元素并将它们包装在 <div>
中?
例如我有
<div class="content">
<p>one</p>
<p>two</p>
<h2> not p</h2>
<p>three</p>
<p>four</p>
<p>five</p>
<h3>not p</h3>
<div>not p</div>
<p>six</p>
<p>seven</p>
</div>
我想要得到一些东西,像这样:
<div class="content">
<div class="wrap">
<p>one</p>
<p>two</p>
</div>
<h2> not p</h2>
<div class="wrap">
<p>three</p>
<p>four</p>
<p>five</p>
</div>
<h3>not p</h3>
<div>not p</div>
<div class="wrap">
<p>six</p>
<p>seven</p>
</div>
</div>
最佳答案
尝试一下,这是一个很好的起点:
$(function(){
const target = 'p',
invert = ':not(' + target + ')',
wrap = '<div class="wrapper">',
breakpoints = $('.content > *'+invert);
breakpoints.each(function(){
$(this).nextUntil(invert).wrapAll( wrap );
});
breakpoints.first().prevUntil(invert).wrapAll( wrap );
});
.wrapper{border:1px solid red;}
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<div class="content">
<p>one</p>
<p>two</p>
<h2> not p</h2>
<p>three</p>
<p>four</p>
<p>five</p>
<h3>not p</h3>
<div>not p</div>
<p>six</p>
<p>seven</p>
</div>
关于javascript - 将相邻的 <p> 元素包装到 <div> 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56853890/