2011-12-19 16 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

だろう。

$('.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ちょうど華麗この(fiddle)を試してみてください。 –

+0

ニースの答え、ありがとう! – Duopixel

関連する問題