我有一个带标题的 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/