如何使用jquery隐藏除一个元素以外的所有元素? [英] How to hide all elements except one using jquery?

查看:200
本文介绍了如何使用jquery隐藏除一个元素以外的所有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有HTML页面:

<head></head>
<body>
  <div>
    <div>
      <div id="myDiv">
      </div>
    </div>
  </div>
</body>

如何隐藏所有div,并使用jquery将myDiv放在体内?

How to hide all divs, and just have the myDiv inside the body using jquery?

更新

页面可能包含其他html元素,例如一些表,锚点,p,而我只想查看myDiv元素.

The page may contain some other html elements such as some tables, anchors, p, and i just want to see the myDiv element.

推荐答案

这应该有效:

$('div:not(#myDiv)').hide();  // hide everything that isn't #myDiv
$('#myDiv').appendTo('body');  // move #myDiv up to the body

更新:

如果您想隐藏所有内容,而不仅仅是div元素,请改用此内容:

If you want to hide EVERYTHING that, not just div elements, use this instead:

$('body > :not(#myDiv)').hide(); //hide all nodes directly under the body
$('#myDiv').appendTo('body');

可能更简单的方法是将页面的整个可隐藏"部分包装在一个大容器元素中,然后直接将其隐藏.

Probably simpler is to wrap the entire "hideable" part of the page in a big container element, and hide that directly though.

像这样:

 <body>
     <div id="contents">
        <!-- a lot of other stuff here -->
        <div id="myDiv>
        </div>
     </div>
 </body>

然后,您可以执行此操作,它变得更加干净和快捷:

Then you can just do this, which is cleaner and faster:

$('#contents').hide();
$('#myDiv').appendTo('body');

这篇关于如何使用jquery隐藏除一个元素以外的所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆