如何使用jQuery删除除第一个之外的所有div?

时间:2011-04-27 08:10:11

标签: jquery

我有html页面,我需要删除除id =“allPage”的div之外的所有div,除了id =“allPage”的div的所有内容。我有下一个代码:

<body>
<div class="page" id="allPage">
    <div id="header">
        <div id="title">
            <h1><a href="/">here</a></h1>
        </div> 
        <!-- Many other divs -->
    </div>
</div>

<script type="text/javascript">
    // Some script
</script>

<!-- Next div maked by dialog of jQuery -->
<div style="display: none; z-index: 100; outline: 0px none;" class="ui-dialog ui-widget ui-widget-content ui-corner-all alert" tabindex="-1" role="dialog" aria-labelledby="ui-dialog-title-CreateWarehouse">
    <div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">
        <span class="ui-dialog-title" id="ui-dialog-title-CreateWarehouse">Create warehouse</span>
        <a href="#" class="ui-dialog-titlebar-close ui-corner-all" role="button"><span class="ui-icon ui-icon-closethick"></span></a>
    </div>

    <div id="CreateWarehouse" class="ui-dialog-content ui-widget-content">

        <div class="Editor ui-widget ui-widget-content" id="AddWarehouseInvoiceControl">
            <form action="#" class="WarehouseInvoice">
                <input type="hidden" class="Id" value="">
                <!-- Some other elements -->
            </form>
        </div>

        <input type="hidden" class="WICreationResult" value="0">
    </div>
</div>

如果我使用它$("body > div:not(#allPage)").remove();,我会收到下一个结果

<body>
<div class="page" id="allPage">
    ...
</div>

<script type="text/javascript">
    // Some script
</script>

<div id="CreateWarehouse" class="" style="display: none;">

    <div class="Editor ui-widget ui-widget-content" id="AddWarehouseInvoiceControl">
        <form action="#" class="WarehouseInvoice">
            <input type="hidden" class="Id" value="">
            <!-- Some other elements -->
        </form>
    </div>

    <input type="hidden" class="WICreationResult" value="0">
</div>

如何删除除id =“allPage”的div之外的所有div?

2 个答案:

答案 0 :(得分:6)

$('body > div:gt(0)').remove();

这将选择body标签的所有<div>子项,索引大于0(这样第一个<div>保持不变)。

http://api.jquery.com/gt-selector/

答案 1 :(得分:5)

$('div').not('#allPage').remove();

$('div:not(#allPage)').remove();