3

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?

4
  • Are you sure you want to "remove all the other div elements"? From the entire page? 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... Commented Mar 9, 2011 at 13:47
  • what if your div is enclosed in another div? 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... Commented Mar 9, 2011 at 13:54

2 Answers 2

7
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();
Sign up to request clarification or add additional context in comments.

10 Comments

use document.getElementsByTagName instead of document.querySelectorAll in for support in browsers that do not support the later.
will $('div').not('#content').remove(); not remove a parent which is a div?
@jAndy caching the 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)
@Itay: .not() filters the current set and removes all matches.,
I don't like this...seems way more verbose and complicated than needed...and not particularly compatible to boot.
|
0

If you want to remove the sibling DIVs, using jQuery, you can write:

$("#content").siblings("div").remove();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.