jQuery 如何使用jquery隐藏除一个元素之外的所有元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1535331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:39:43  来源:igfitidea点击:

How to hide all elements except one using jquery?

jquery

提问by Amr Elgarhy

I have HTML page:

我有 HTML 页面:

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

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

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

Update

更新

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

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

回答by TM.

This should work:

这应该有效:

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

Update:

更新:

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

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

$('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.

可能更简单的是将页面的整个“可隐藏”部分包装在一个大容器元素中,然后直接隐藏它。

Like so:

像这样:

 <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');

回答by Chris Johnson

A nice general approach:

一个很好的通用方法:

$('#the_id').siblings().hide()
$('#the_id').parents().siblings().hide()

Works for any element type.

适用于任何元素类型。

回答by Chad

If you're objective is just to see that content and not see anything else, you can always just do this. You don't need jQuery:

如果您的目标只是查看该内容而不查看其他任何内容,那么您始终可以这样做。你不需要jQuery:

document.body.innerHTML=document.getElementById('myDiv').innerHTML;

回答by Anthony Mills

$("div").each(function () { $(this).toggle(!!this.id); });

Note that this will explicitly show#myDiv. If you just want to hide the other divs:

请注意,这将显式显示#myDiv。如果您只想隐藏其他 div:

$("div:not(#myDiv)").show();

Then you can do:

然后你可以这样做:

$("#myDiv").appendTo("body");