John
John

Reputation: 9456

How to remove everything within a DIV except for one element?

I have the following 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>

I want to remove everything within div.item except for the image. I tried using this bit of code, but the text node still remains within the div.

$('.item').contents().not('img').remove();

Any suggestions?

Here's my JSFiddle that you can fiddle with: http://jsfiddle.net/pSmDW/

Upvotes: 11

Views: 12661

Answers (4)

Brett DeWoody
Brett DeWoody

Reputation: 62773

For jQuery v1.9.1 and below the following will work:

$('.item').contents(':not("img")').remove();

This will look for all elements (including text nodes) that aren't images and remove them.

$(document).ready(function() {
  $('.item').contents(':not("img")').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="item">
    <img src="https://via.placeholder.com/350x150"/>
    TEXT NODE
    <span class="some_class">What the funk?</span>
    <form>What the monkey</form>
</div>

For jQuery > 1.9.1 there is an issue when using .contents() with :not(). As a workaround you can grab the image, then replace the .html() of the element with the image.

$(document).ready(function() {
  var imgNode = $('.item').find('img');
  $('.item').html(imgNode);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item">
    <img src="https://via.placeholder.com/350x150"/>
    TEXT NODE
    <span class="some_class">What the funk?</span>
    <form>What the monkey</form>
</div>

Upvotes: 2

Dessus
Dessus

Reputation: 2177

Try this: $('.item').contents(':not(img)').remove();

Upvotes: 20

Tom Gillard
Tom Gillard

Reputation: 575

The TEXT NODE needs to be wrapped in a html tag such as span. I tried this with the JSFiddle you provided and worked no problems. http://jsfiddle.net/pSmDW/1/

Good luck! Tom

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

Upvotes: 0

user1106925
user1106925

Reputation:

var itm = $('.item');
var img = itm.children('img');
itm.empty().append(img);

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


If there's any data or handlers on the image, we can use .detach().

var itm = $('.item');
var img = itm.children('img').detach();
itm.empty().append(img);

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


If there are several of these, you'll want to use .each().

$('.item').each(function() {
    var img = $(this).children('img').detach();
    $(this).empty().append(img);
});

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

Upvotes: 7

Related Questions