如何抓取<h2>之间的HTML
how to grab the html between <h2>
我有这个HTML块:
<h2>heading A</h2>
<p>paragraph 1 of A</p>
<p>paragraph 2 of A</p>
<h2>heading B</h2>
<ul id="list-B">
<li>list B1</li>
<li>list B2</li>
</ul>
<p>paragraph 1 B</p>
<h2>...</h2>
..
我需要抓取每个"h2
和它的内容",并将它们分组成这样:
<div class="news">
<h2>heading A</h2>
<div class="content">
<p>paragraph 1 of A</p>
<p>paragraph 2 of A</p>
</div>
</div>
<div class="news">
<h2>heading B</h2>
<div class="content">
<ul id="list-B">
<li>list B1</li>
<li>list B2</li>
</ul>
<p>paragraph 1 B</p>
</div>
</div>
...
有什么建议吗?
给你:
$( 'h2' ).each(function () {
$( this ).nextUntil( 'h2' ).andSelf().wrapAll( '<div class="news" />' );
$( this ).nextAll().wrapAll( '<div class="content" />' );
});
现场演示: http://jsfiddle.net/phJPq/2/
不使用jQuery:
function reFormat() {
// Collect h2 elements
var h, hs = document.getElementsByTagName('h2');
var node;
var d, od = document.createElement('div');
od.className = 'news';
var d2, od2 = od.cloneNode(false);
od2.className = 'content';
// For each h2
for (var i=0, iLen=hs.length; i<iLen; i++) {
h = hs[i];
d = od.cloneNode(true);
d2 = od2.cloneNode(true);
node = h.nextSibling;
// Append all siblings to new div until get to next h2
while (node && node != hs[i + 1]) {
d2.appendChild(node);
node = h.nextSibling;
}
// Replace h2 with div, then insert into div
h.parentNode.replaceChild(d, h);
d.appendChild(h);
d.appendChild(d2);
}
}
相关文章:
- 函数参数中的数据与指定变量之间的任何性能差异
- 全局变量和全局对象的属性之间有什么区别吗
- java.net和javascript之间正则表达式的差异
- JavaScript中的函数和对象之间没有区别吗?
- 获取@ResponseBody的一部分作为主干和Spring MVC控制器之间的参数
- Jquery在函数之间传递表行
- 根据某些条件在视图之间切换
- 在控制器和数据对象之间同步数据
- d3中堆栈函数和嵌套函数之间的差异
- JQuery:在页面之间滑动
- 如何使用JavaScript查找1和N之间的所有数字的总和
- 操作放置在画布上的元素之间的连接
- 在下划线中使用_(obj).map(callback)和_.map(obj,callback)之间的区别
- jquery在表单之间切换
- Nodejs API控制器,用于在API之间切换
- 如何在aspx页面之间传递参数
- 在索引.html和应用.js [node.js] 之间共享变量
- 什么是&&在没有if的行中的变量之间
- 如何选择两个h2之间的所有元素
- 隐藏2个h2标签之间的所有内容