javascript - 在javascript中的标题标签之间分组html

标签 javascript jquery html

我有一个带标题的 html 页面。我想使用 javascript 或任何 native 库对标题下的内容 (html) 进行分组。我怎样才能做到这一点? 示例如下

<div>
  <h2>Main</h2>
  <p> Content goes here</p>
  <img src="someimg.jpg"/>
  <h2>Main2</h2>
  <p> Content goes here</p>
  <img src="someimg.jpg"/>
  <h2>Main3</h2>
  <p> Content goes here</p>
  <img src="someimg.jpg"/>
</div>

输出应该是

<div>
  <div>
    <h2>Main</h2>
    <p> Content goes here</p>
    <img src="someimg.jpg"/>
  </div>
  <div>
    <h2>Main2</h2>
    <p> Content goes here</p>
    <img src="someimg.jpg"/>
  </div>
  <div>
    <h2>Main3</h2>
    <p> Content goes here</p>
    <img src="someimg.jpg"/>
  </div>
</div>

最佳答案

试试这个:

$("h2").each(function(){
    $(this).nextUntil("h2").addBack().wrapAll("<div class='wrapper'>");
});
.wrapper{
  border-bottom:1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div>
  <h2>Main</h2>
  <p> Content goes here</p>
  <img src="someimg.jpg"/>
  <h2>Main2</h2>
  <p> Content goes here</p>
  <img src="someimg.jpg"/>
  <h2>Main3</h2>
  <p> Content goes here</p>
  <img src="someimg.jpg"/>
</div>

关于javascript - 在javascript中的标题标签之间分组html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44381863/

相关文章:

javascript - 基于对象数组创建垂直列表

javascript - 使用ajax将复选框多个数组传递给php

javascript - Jquery 单击首先不适用于输入元素

javascript - 将数据库下载到本地文件系统并使用 opendatabase 导致没有这样的表错误消息

javascript - 移动设备上的 Fancybox 内联弹出窗口不随页面滚动移动

javascript - JQuery/CSS 动画转换减慢页面

javascript - 如何获取点击了哪个元素?

javascript - 如何使页面宽度动态达到一定限制?

javascript - CSS border-right, border-bottom 在 firefox 中不显示

html - 将 Bootstrap 面板宽度设置为文本宽度