如何抓取<h2> </h2>之间的html

时间:2011-12-15 02:27:06

标签: javascript jquery html

我有这个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>
...

有什么建议吗?

2 个答案:

答案 0 :(得分:7)

你走了:

$( 'h2' ).each(function () {
    $( this ).nextUntil( 'h2' ).andSelf().wrapAll( '<div class="news" />' );
    $( this ).nextAll().wrapAll( '<div class="content" />' );
});

现场演示: http://jsfiddle.net/phJPq/2/

答案 1 :(得分:0)

没有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);
  }
}