MShack
MShack

Reputation: 652

jquery remove all div but 1 not working

I am trying to remove all div elements while only keeping one to show http://jsfiddle.net/m5pt4kxa/

I tried all of these but none work , they remove everything and don't show the #mfloverview

$('#body_home div:not(#mfloverview)').remove();
$('#body_home div').not('#mfloverview').remove();
$('div').not('#mfloverview').remove();

Here is the HTML

<body id="body_home">
  <div id="home" class="pagebody">
    <div></div>
    <div></div>
    <div></div>
    <div id="mfloverview"></div>
  </div>
</div>

Upvotes: 0

Views: 56

Answers (4)

Pratik
Pratik

Reputation: 307

$("#body_home div").not(document.getElementByid('mfloverview')).remove()

Upvotes: 0

Joao Paulo
Joao Paulo

Reputation: 1103

Try

$('#home').find(":not(#mfloverview)").remove();

or

$('div').find(":not(#mfloverview)").remove();

Upvotes: 0

Mithun Satheesh
Mithun Satheesh

Reputation: 27845

Actually when you target all divs other than #mfloverview, you are targeting its parent divs also which case it also to be removed as its a child in it.

Try removing the divs inside #home but not #mfloverview like the code below.

$('#home div').not('#mfloverview').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="body_home">
  <div id="home" class="pagebody">
    <div>s</div>
    <div>d</div>
    <div>f</div>
    <div id="mfloverview">g</div>
  </div>
</div>

Upvotes: 0

George
George

Reputation: 36794

Your selections select all div elements that don't have #mfloverview. This includes #home. Your code removes that element and everything inside and finishes.

Make your selection a little more particular:

$('#body_home #home div').not('#mfloverview').remove();

So the selected <div> elements must be a descendant of #home, which must be a descendant of #body_home

JSFiddle

Upvotes: 2

Related Questions