在div中包裹流浪文本

时间:2011-12-19 22:53:10

标签: jquery

如何选择“没有包含标签的任何内容”来在jQuery中添加包装器?例如:

<div class="post">
    <div class="whatever">This should remain untouched</div>
    I want to wrap this in div.red
</div>

结果就是这个

<div class="post">
    <div class="whatever">This should remain untouched</div>
    <div class="red">I want to wrap this in div.red</div>
</div>

1 个答案:

答案 0 :(得分:5)

您正在尝试选择文本节点。试试这个(fiddle):

$('.post').each(function() {
    var data = [];
    $(this).contents().each(function() {
        if ( this.nodeType === Node.TEXT_NODE ) {
            data.push(this);
        }
    }).end().append( $('<div class="red" />').append(data) );
});

<强> HTML

<div class="post">
    <div class="whatever">This should remain untouched</div>
    I want to wrap this in div.red
</div>

<强> CSS

.red{background:red}