除了一个元素之外,如何删除DIV中的所有内容?

Joh*_*ohn 12 jquery

我有以下HTML:

<div class="item">
    <img src="http://mintywhite.com/images/wg/0904/05rssfeedicons/rss-feed-icons11.jpg"/>
    TEXT NODE
    <span class="some_class">What the funk?</span>
    <form>What the monkey</form>
</div>
Run Code Online (Sandbox Code Playgroud)

我想删除div.item除图像之外的所有内容.我尝试使用这段代码,但文本节点仍然在div.

$('.item').contents().not('img').remove();
Run Code Online (Sandbox Code Playgroud)

有什么建议?

这是我可以摆弄的JSFiddle:http://jsfiddle.net/pSmDW/

Des*_*sus 18

试试这个: $('.item').contents(':not(img)').remove();


小智 7

var itm = $('.item');
var img = itm.children('img');
itm.empty().append(img);
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/pSmDW/2/


如果图像上有任何数据或处理程序,我们可以使用.detach().

var itm = $('.item');
var img = itm.children('img').detach();
itm.empty().append(img);
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/pSmDW/3/


如果有这些,你会想要使用.each().

$('.item').each(function() {
    var img = $(this).children('img').detach();
    $(this).empty().append(img);
});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/pSmDW/4/