insanity
insanity

Reputation: 1178

Clear all Content of the div except few elements

Suppose i have a div in which i have many elements like this

<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>

I want to remove all the elements inside this div except these two buttons. I have used

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

but it will clear all the contents inside it. how can i filter it

Upvotes: 0

Views: 515

Answers (2)

Felix
Felix

Reputation: 38102

You can use replaceWith():

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

Fiddle Demo


If you want to keep the parent div as well, then you can do like @adeneo suggestion:

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

Upvotes: 2

adeneo
adeneo

Reputation: 318182

How about removing all the children except the inputs ?

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

FIDDLE

Upvotes: 7

Related Questions