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?
var 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();
document.getElementsByTagName instead of document.querySelectorAll in for support in browsers that do not support the later.$('div').not('#content').remove(); not remove a parent which is a div?all_div_nodes[len] would perform much faster and why do need to check for the presence of parentNode for each div? (this would be required only if your html document is malformed).not() filters the current set and removes all matches.,
divelements, ie not ancestors (that would mean removing the#contentnode itself) nor descendants...