The remove() and empty() methods


In the last couple of chapters, we have worked with adding new elements to a page, but of course jQuery can help you remove them as well. There are mainly two methods for this: remove() and empty(). The remove() method will delete the selected element(s), while the empty() method will only delete all child elements of the selected element(s). The following example should illustrate the difference – be sure to click the links in the right order though:

<a href="javascript:void(0);" onclick="$('#divTestArea1').empty();">
empty() div</a>  
<a href="javascript:void(0);" onclick="$('#divTestArea1').remove();">
remove() div</a>
<div id="divTestArea1" style="height: 100px; width: 300px; padding: 20px;
border: 1px solid silver; background-color: #eee;">
        <b>Bold text</b>
        <i>Italic text</i>
</div>

The first link will call the empty() method on our test div, removing all the child elements. The second link will remove the entire div, including any child elements. Pretty simple stuff.

The remove() method comes with one optional parameter, which allows you to filter the elements to be removed, using any of the jQuery selector syntaxes. You could of course achieve the same simply by doing the filtering in your first selector, but in some situations, you may be working on a set of already selected elements. Check out this example of it in use:

<a href="javascript:void(0);" onclick="$('#divTestArea2 b').remove('.more');">
remove() more bold</a>
<div id="divTestArea2" style="height: 100px; width: 300px; padding: 20px;
border: 1px solid silver; background-color: #eee;">
        <b>Bold text</b><br />
        <b class="more">More bold text</b><br />
        <b class="more">Even more bold text</b><br />
</div>

We start out by selecting all bold tags inside our test div. We then call the remove() method on the selected elements, and pass in the .more filter, which will make sure that we only get elements which uses the class “more”. As a result, only the last two bold texts are removed.

You can of course use even more advanced selectors as a filter too. Have a look at the “Selectors” topic of this tutorial for inspiration.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s