最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

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();
发布评论

评论列表(0)

  1. 暂无评论