admin管理员组文章数量:1396787
Lets say I have a webpage, and all I'm interested is the div with id "content", i.e:
<div id="content"></div>
How do I remove all the other div elements, and just display the div I want?
Lets say I have a webpage, and all I'm interested is the div with id "content", i.e:
<div id="content"></div>
How do I remove all the other div elements, and just display the div I want?
Share Improve this question edited Mar 9, 2011 at 14:10 David Tang 93.7k32 gold badges168 silver badges149 bronze badges asked Mar 9, 2011 at 13:42 chutsuchutsu 14.1k20 gold badges66 silver badges86 bronze badges 4- Are you sure you want to "remove all the other div elements"? From the entire page? – thirtydot Commented Mar 9, 2011 at 13:44
-
I suppose you only mean to remove sibling
div
elements, ie not ancestors (that would mean removing the#content
node itself) nor descendants... – Nicolas Le Thierry d'Ennequin Commented Mar 9, 2011 at 13:47 - what if your div is enclosed in another div? – Livingston Samuel Commented Mar 9, 2011 at 13:54
- @thirtydot yes, because I'm only interested in the content of the webpage, if the webpage has like #nav, #footer, #header which are parent nodes, I don't want it... all I want is the #content and its child elements... – chutsu Commented Mar 9, 2011 at 13:54
2 Answers
Reset to default 7var all_div_nodes = document.querySelectorAll('div'),
len = all_div_nodes.length,
current = null;
while( len-- ) {
current = all_div_nodes[len];
if( current.parentNode ) {
if( current .id !== 'content' )
current .parentNode.removeChild( current );
}
}
If you can afford using a library like jQuery, this would be even more trivial:
$('div').not('#content').remove();
If you want to remove the sibling DIVs, using jQuery, you can write:
$("#content").siblings("div").remove();
本文标签: htmlHow to remove div elements with JavascriptStack Overflow
版权声明:本文标题:html - How to remove div elements with Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744145061a2592797.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论