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/
Given an HTML document containing div elements and the task is to remove the existing HTML elements using jQuery. To remove elements and its content, jQuery provides two methods: remove(): It removes the selected element with its child elements. empty(): It removes the child element from the selected elements.
To remove elements and content, there are mainly two jQuery methods: remove() - Removes the selected element (and its child elements) empty() - Removes the child elements from the selected element.
The empty() method removes all child nodes and content from the selected elements. Note: This method does not remove the element itself, or its attributes. Tip: To remove the elements without removing data and events, use the detach() method. Tip: To remove the elements and its data and events, use the remove() method.
Try this: $('.item').contents(':not(img)').remove();
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With