Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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/

like image 673
John Avatar asked Jan 05 '12 02:01

John


People also ask

How do I delete all content inside a div?

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.

How to remove div from div using jQuery?

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.

How to remove all elements from div in jQuery?

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.


2 Answers

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

like image 59
Dessus Avatar answered Oct 11 '22 03:10

Dessus


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/

like image 42
user1106925 Avatar answered Oct 11 '22 03:10

user1106925