TOC
Need to learn JavaScript? jQuery is a JavaScript framework, so if you don't already know about the JavaScript programming language, we recommend that you learn it now: Learn JavaScript

The community is working on translating this tutorial into Igbo, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

DOM manipulation:

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.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!