jQuery在<hr>标记之间包装文本和元素

use*_*688 5 jquery jquery-selectors

我需要包装两个<hr>元素之间的所有内容,包括自由文本.

鉴于此来源:

<hr class=begin>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  <a href=mauris.html>Mauris</a> id diam turpis, et faucibus nunc.
  <div><img src=foo.png /></div>
<hr class=end>
Run Code Online (Sandbox Code Playgroud)

我需要在hr.beginhr.end标签之间包装所有内容,如下所示:

<hr class=begin>
  <div class=content>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    <a href=mauris.html>Mauris</a> id diam turpis, et faucibus nunc.
    <div><img src=foo.png /></div>
  </div>
<hr class=end>
Run Code Online (Sandbox Code Playgroud)

我不能使用像.nextUntil('hr.end')这样的方法,因为这不会选择未标记的文本.

use*_*716 5

更新

我比以前更喜欢这个版本:http://jsfiddle.net/LbmCg/3/

(部分灵感来自JP给出的答案.)

$('hr.begin').each(function(){
    var $set = $();
    var nxt = this.nextSibling;
    while(nxt) {
        if(!$(nxt).is('hr.end')) {
            $set.push(nxt);
            nxt = nxt.nextSibling;
        } else break;
    } 
   $set.wrapAll('<div class="content" />');
});
Run Code Online (Sandbox Code Playgroud)

原始答案

试试这个:http://jsfiddle.net/LbmCg/

如果要包装多个套件,则需要进行一些调整.

var foundBegin = false;
var foundEnd = false;

$('hr.begin').parent()
    .contents()
    .filter(function() {
        if($(this).is('hr.begin')) {
            foundBegin = true;
        }
        if($(this).is('hr.end')) {
            foundEnd = true;
        }
        return foundBegin && !foundEnd;
    })

    .wrapAll('<div class="content"/>');?
Run Code Online (Sandbox Code Playgroud)

jQuery .contents()返回包括文本节点在内的所有节点.所以在这里我们遍历到.parent()hr.begin,让使用它的所有节点.contents(),然后通过他们进行筛选,跟踪,当我们发现的开始和结束,只有返回它们之间的所有元素.

然后我们用它.wrapAll()来包装它们div.content.


编辑:如果要包装多个集合,请尝试以下方法:http://jsfiddle.net/LbmCg/1/

编辑:在两个例子中清理了一点.