javascript - 一个分区中的所有段落

标签 javascript jquery html css wordpress

如您所知,Wordpress 会像这样自动生成帖子的 html:

<h2>Heading Example</h2>
<p>Text here</p>
<p>Text here</p>
<p>Text here</p>
<p>Text here</p>
<h3>Heading Example</h3>
<p>Text here</p>
<p>Text here</p>
<p>Text here</p>
<p>Text here</p>
<h3>Heading Example</h3>

但我想在一个 div 中的标题之间制作所有段落,如下所示:

<h2>Heading Example</h2>
<div class="paragraphblock">
<p>Text here</p>
<p>Text here</p>
<p>Text here</p>
<p>Text here</p>
</div>
<h3>Heading Example</h3>
<div class="paragraphblock">
<p>Text here</p>
<p>Text here</p>
<p>Text here</p>
<p>Text here</p>
</div>
<h3>Heading Example</h3>

我该怎么做?

最佳答案

使用nextUntil()wrapAll()each()循环。

$('h2,h3').each(function(){
  $(this).nextUntil(':not(p)').wrapAll('<div>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<h2>Heading Example</h2>
<p>Text here</p>
<p>Text here</p>
<p>Text here</p>
<p>Text here</p>
<h3>Heading Example</h3>
<p>Text here</p>
<p>Text here</p>
<p>Text here</p>
<p>Text here</p>
<h3>Heading Example</h3>

另一种选择。

$('h2,h3,p').each(function(){
  console.log(this.tagName)
  if(this.tagName == 'H2' || this.tagName == 'H3'){
    $div = $('<div>');
    $(this).after($div);
  } else {
    $div.append(this);
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<h2>Heading Example</h2>
<p>Text here</p>
<p>Text here</p>
<p>Text here</p>
<p>Text here</p>
<h3>Heading Example</h3>
<p>Text here</p>
<p>Text here</p>
<p>Text here</p>
<p>Text here</p>
<h3>Heading Example</h3>

关于javascript - 一个分区中的所有段落,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36751529/

相关文章:

javascript - +!! if 语句中的运算符

javascript - 来自数组的选择器 - Jquery/Javascript

html - 宽度自动和宽度 100% 之间的区别

HTML 表格不能跨越多个列的文本框

javascript - IE 触发除了点击以外的任何东西

javascript - 笛卡尔坐标到极坐标导致 NaN

jquery 文件树 - 默认情况下打开所有文件夹?

javascript - this.appendChild 不是一个函数

javascript - jQuery:循环重复切换显示/隐藏多个以数字命名的类

javascript - Handsontable中的Handsontable下拉高度调整