清除除少数元素之外的div的所有内容

时间:2014-02-28 07:23:44

标签: javascript jquery html css

假设我有一个div,其中有很多像这样的元素

<div id="ans" style="background-color: #FFD993;
    color: #FFF;
    overflow:auto;
    border: 1px outset #4f6417;
    -moz-border-radius: 8px;
    -webkit-border-radius: 8px;width:100%;text-align: center;height:33%;margin-bottom:    0px;">
    <input type="button" id="again" value="See Again"></input>
    <input type="button" id="prac" value="Practice"></input>
    <img id="theImg" src="result/' + rand + '.png" width="40%" height="60%"/>
    <a href="1.html">1</a>
    <a href="2.html">2</a>
    <p>This is Paragraph</p>
</div>

除了这两个按钮之外,我想删除此div中的所有元素。我用过

$('#ans').empty();

但它会清除其中的所有内容。我怎样才能过滤它

2 个答案:

答案 0 :(得分:7)

如何删除除输入之外的所有孩子?

$('#ans').children(':not(input[type="button"])').remove();

FIDDLE

答案 1 :(得分:2)

您可以使用 replaceWith()

$('#ans').replaceWith(function() { return $('input', this) });

<强> Fiddle Demo


如果你想保留父div,那么你可以像@adeneo建议一样:

$('#ans').find(':not(input)').remove();