Removing elements with jQuery

Removing elements with jQuery is quite a simple task. Through the remove() method we can actually remove elements from the DOM tree. In our example, we have a series of panels with the following styles:

body {
 margin: 0 auto;
 width: 470px;
 padding: 15px 0 10px 0;
 font: 76% Arial, sans-serif;
h2 {
 margin: 0;
 padding: 0 0 0.3em;
 font: 1.4em "Trebuchet MS", Trebuchet, sans-serif;
 color: #080;
p {
 margin: 0;
 padding: 0 0 0.5em;
.panel {
 background: #edf5e1;
 padding: 10px 20px 10px;
 position: relative;
 border-top: solid 2px #c4df9b;
 height: 100%;
 font-size: 1.1em;
 margin-bottom: 1em;
.panel .remove {
 position: absolute;
 top: 10px;
 right: 10px;
 cursor: pointer;

First of all, we need to add a trigger to be used with the class .remove. We'll use an image that we'll insert through jQuery. Here are the first lines of code:

var button = $('<img/>').attr('src', 'img/delete.gif').addClass('remove');

Since each panel forms a new containing block thanks to the declaration position: relative, our image will be inserted in the top right corner of each panel. Now we can complete our task with the following lines of code:

$('.panel .remove').each(function() {
        var $img = $(this);
        $ {
 $img.parent().animate({'opacity':'hide'}, 'slow', function() {

When we click on each image, the parent panel will disappear thanks to the animate() method. Further, since this method also accepts a callback function as one of its arguments, the parent panel is also removed from the DOM tree. You can see the final result here.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.