繁体   English   中英

包装相邻 <p> 元素成一个 <div>

[英]Wrap adjacent <p> elements into a <div>

是否可以选择所有彼此相邻的<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> 

好吧,该算法非常简单:遍历<p>节点的数组,如果先前的兄弟姐妹是.wrapper本身,则将该项目扔到先前的.wrapper ,否则创建一个:

 [...$('p')].forEach((p,i) => $(p).prev().is('.wrapper') && i > 0 ? $(p).prev().append(p) : $('<div class="wrapper"></div>').insertBefore(p).append(p)) 
 .wrapper {background: lightblue} 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM