如何使用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');