开发者

Separate an HTML document with headings into sections

开发者 https://www.devze.com 2023-03-07 12:04 出处:网络
How can I separate in sections a docum开发者_如何学Pythonent with headings? Convert this <h1>chapter 1</h1>

How can I separate in sections a docum开发者_如何学Pythonent with headings?

Convert this

<h1>chapter 1</h1>
<p>lorem ipsum</p>
<p>sit amet</p>
<h1>chapter 2</h1>
<p>lorem ipsum</p>
<p>sit amet</p>

into this

<div class="chapter">
  <h1>chapter 1</h1>
  <p>lorem ipsum</p>
  <p>sit amet</p>
</div>
<div class="chapter">
  <h1>chapter 2</h1>
  <p>lorem ipsum</p>
  <p>sit amet</p>
</div>

I guess with jQuery this is easy, but I haven't figured how yet.


Try something like this:

$('h1').each( function(){
    $(this).nextUntil('h1').andSelf().wrapAll('<div class="chapter">');
});

Example: http://jsfiddle.net/redler/YVF2w/


I guess with jQuery this is easy, but I haven't figured how yet.

Don't do this with jQuery. Write this into your HTML, or use whatever view / template engine your using to write your HTML like this.

Also there is such a thing as <section> and <header> I would recommend using them (but since they are HTML5 you might need html5 shim).


Of course if you want to do it witout jQuery, it's not that hard:

/* Convert a list to an array
 */
function listToArray(list) {
  var result = [],
      i = list.length;
  while (i--) result[i] = list[i];
  return result;
}


/* Wrap elements with tagName in a div until next sibiling
 * with same tagName
 */
function wrapSiblings(tag) {
  tag = tag.toLowerCase();

  // Take elements out of document while processing so
  // need to convert NodeList to array
  var el, els = listToArray(document.getElementsByTagName(tag));
  var div = document.createElement('div');
  div.className = 'chapter';
  var oDiv, oEl;

  for (var i=0, iLen=els.length; i<iLen; i++) {
    el = els[i];
    oEl = el.nextSibling;
    oDiv = div.cloneNode(false);

    // Shift all siblings into Div
    while (oEl && !(oEl.tagName && oEl.tagName.toLowerCase() == tag)) {
      oDiv.appendChild(oEl);

      // Moved sibling, get nextSibling - live list!
      oEl = el.nextSibling;
    }

    // Replace el with div, then put el into div
    el.parentNode.insertBefore(oDiv, el);
    oDiv.insertBefore(el, oDiv.firstChild);
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号