2011-12-19 55 views
3

如何选择“没有包含标签的任何东西”来在jQuery中添加包装?例如:在div中包裹杂散文本

<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> 

回答

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} 
+0

+100只是辉煌。 – 2011-12-20 01:12:57

+0

很好的答案,谢谢! – Duopixel 2011-12-20 02:15:56