html - How to remove div elements with Javascript? - Stack Overflow

Lets say I have a webpage, and all I'm interested is the div with id "content", i.e:<

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
Add a ment  | 

2 Answers 2

Reset to default 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();

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

相关推荐

  • html - How to remove div elements with Javascript? - Stack Overflow

    Lets say I have a webpage, and all I'm interested is the div with id "content", i.e:<

    8天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信