Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

empty() everything except a particular element

Tags:

jquery

Using jQuery's empty() method, can I prevent a particular element from being removed from the DOM, while all other elements are removed?

For instance:

<div id="container">
    <div id="noRemove"></div>
    ... more content ...
</div>

When I make this call with jQuery $("#container").empty(), how can I prevent the removal of noRemove while still removing the rest of the content inside container?

like image 426
FastTrack Avatar asked Dec 01 '22 23:12

FastTrack


2 Answers

Use the following, it will remove everything from the container but the element whose id is noRemove:

$('#container').contents().filter(function () {
    return this.id != "noRemove";
}).remove();

DEMO.

like image 35
João Silva Avatar answered Dec 09 '22 20:12

João Silva


You can't using the empty function alone. Here's one way you could do it:

var $container = $('#container'),
    $noRemove = $container.find('#noRemove');

$container.html($noRemove);

Here's a fiddle: http://jsfiddle.net/joplomacedo/R4cu5/

like image 130
João Paulo Macedo Avatar answered Dec 09 '22 19:12

João Paulo Macedo