如何选择“没有包含标签的任何内容”来在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>
答案 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}