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();
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744145067a4560383.html
评论列表(0条)