开发者

jQuery how to delete or hide all html except selected <div>

Given the f开发者_Go百科ollowing 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 bar divs, so I would end up with only:

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

I have tried: $('.foo :not(.bar)').hide(); but elements that don't meet this selection are obviously remaining.

Is there a selector that will match everything, or should I extract the bar divs to a new var?


You will need to wrap the content inside the .foo element, between the .bar elements in seperate elements. Otherwise, you will have no hide these bastards without hiding the entire .foo element.

<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, your should be able to do something like this:

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

Or, if you do not care about being able to undo:

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


Quick 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜