JQuery how to remove or hide all html except selected <div>

Given the following markup:

<div class=foo>
  <!-- comments -->
  some junk content
  <input type=button value=click />
  <div class=bar>
    good content
  </div>
  more junk content
  <div class=bar>
    more good content
  </div>
  even more junk
</div>

      

I need to remove everything except the div div, so I end up with only:

  <div class=bar>
    good content
  </div>
  <div class=bar>
    more good content
  </div>

      

I've tried: $('.foo :not(.bar)').hide();

but items that don't match this selection obviously remain.

Is there a selector that will match all, or should I extract the div div into a new var?

+2


source to share


2 answers


Fast and Dirty:



$(function(){
    var html = [];
    $('.bar').each(function(i, item) { html.push($(this).html()); });
    $('.foo').html('<div class="bar">' + html.join('</div><div class="bar">') + '</div>');
});

      

0


source


You will need to wrap the content inside the element .foo

between the elements .bar

in separate elements. Otherwise, you won't hide these bastards without hiding the whole element .foo

.

<div class=foo>
  <!-- comments -->
  <div>some junk content</div>
  <input type=button value=click />
  <div class=bar>
    good content
  </div>
  <div>more junk content</div>
  <div class=bar>
    more good content
  </div>
  <div>even more junk</div>
</div>

      

With such wrappers in place, you should be able to do something like this:



$(".foo > *:not(.bar)").hide();

      

Or, if you don't want to undo:

$(".foo > *:not(.bar)").remove();

      

+3


source







All Articles