How to remove div elements using Javascript?

Suppose I have a web page, and everyone is interested in this DIV with the identifier "content", that is:

<div id="content"></div>

How to remove all other div elements and just display the div I want?

+3
source share
2 answers
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 to use the jQuery library, this will be even more trivial:

$('div').not('#content').remove();
+7
source

If you want to remove child DIV files using jQuery, you can write:

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

All Articles