Get up to 80 % extra points for free! More info:

Lesson 4 - Removing contents in jQuery (DOM)

In the previous lesson, Replacing contents & cloning with jQuery (DOM), we learned to replace and clone contents of the page using the jQuery JavaScript library. In today's tutorial, we're going to show how to remove contents and, as always, try different approaches with examples.

Let's create an HTML file and a JS file as always. We'll insert the basic structure into the JS file.

$(function(){
    // The code here is executed not before the page is loaded
});

We'll place the following code into the HTML file:

<ul>
    <li>Sunday</li>
    <li>Monday</li>
    <li>Tuesday</li>
    <li>Wednesday</li>
    <li>Thursday</li>
    <li>Friday</li>
    <li>Saturday</li>
</ul>

And we'll add styles to the document as well:

ul {
    list-style-type: none;
    margin: 0px;
    padding: 0px;
}

ul li {
    font-family: 'Open Sans';
    font-size: 18px;
    margin: 10px 20px;
    padding: 5px 10px;
    background: #0080C0;
    width: 100px;
    color: #ededed;
}

Our document looks like this so far:

Your page
localhost

We're going to learn how to remove contents using jQuery methods, those are remove(), empty(), and detach(). Let's introduce them!

remove()

The remove() method removes selected elements from the DOM for good. Using it is simple as always, we'll just write:

$('ul li').remove();

The result:

Your page
localhost

Now we removed all the list items.

Example #1

Let's try to remove the items when clicked. We can do this just by assigning the onclick event to the list items using the on('click') method. We'll pass an anonymous function with event handling as the second parameter. Inside, we'll remove the item that was clicked on. We can get it using $(this).

$("ul li").on('click', function() {
    $(this).remove();
});

The live demo:

Your page
localhost

Awesome, everything works. By the way, using the $() function, we can wrap not only the this variable but any element in pure JavaScript on which we can then call jQuery methods.

Let's try the next example.

Example #2

What if we need to remove all elements containing a certain word or a part of it, e.g. "sday"? The "additional selector, filter(), will be useful for this. It'll filter our selector. In filter(), we can use ` which will select all elements containing the text 'sday'. Be careful, the filter is case sensitive, meaning the upper case and lower case letters are treated as distinct.

$('ul li').filter(":contains('sday')").remove();

The result:

Your page
localhost

Impressive, isn't it? The syntax is still pretty long, though. Since the remove() method allows us to use a selector as an argument, we can change our code to:

$('ul li').remove(":contains('sday')");

Which causes the same effect. Let's try to remove Saturday and Sunday. We'll use ":contains('Saturday'), :contains('Sunday')" as the selector.

$('ul li').remove(":contains('Saturday'), :contains('Sunday')");

Now we know when to go to school or work :) :

Your page
localhost

Because we have already practiced remove() in depth, let's move on.

empty()

The empty() method removes all the contents of a given element. The method doesn't require any arguments.

Example #3

Let's show how to empty the "Tuesday" item. Let's assign id="day3" to the Tuesday item.

<ul>
    <li>Sunday</li>
    <li>Monday</li>
    <li id="day3">Tuesday</li>
    <li>Wednesday</li>
    <li>Thursday</li>
    <li>Friday</li>
    <li>Saturday</li>
</ul>

The JS code:

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

The result:

Your page
localhost

It's simple.

Example #4

If we wanted to empty an element containing partial text, we can use filter() again.

$('ul li').filter(':contains("sday")').empty();

The result:

Your page
localhost

The approach where we passed a selector as an argument won't work here. You can try it.

$('ul li').empty(':contains("e")');

You will see that the empty() method ignores the argument and works just as nothing was passed.

detach()

This method cuts out an element (similarly to when we use Ctrl + X) and allows us to store it into a variable.

Example #5

Let's create a paragraph under our list. It'll contain the text "Nothing in there".

We'll add the following to our HTML:

<p>Nothing in there</p>

Now let's try to detach the "Tuesday" item (with the #day3 id). After cutting it out, we'll insert the #day3 element into the paragraph, overwriting its contents.

$('p').text($('#day3').detach().text());

The result:

Your page
localhost

For this particular example, using the append() method would be more appropriate. Well, let's show how to use detach() in a better way!

Example #6

The detach() method is useful when we want to select some elements and then insert them somewhere. Let's make a minigame. When any of our list items is clicked, we'll detach it and store it into an array. When the paragraph is clicked, we'll insert all the items of the array inside.

We'll create the array before registering on('click'). We'll name the variable e.g. storage.

let storage = [];

When the paragraph is clicked, we'll empty it using empty(). Then we'll call the $.each() method to which we'll pass storage as the parameter, the variable to work with. Next, we'll create an anonymous function which will request parameters i and v. i as the index and v as the value.

let storage = [];

$('ul li').on('click', function() {
    storage.push($(this).detach());
});

$('p').on('click', function() {
    let that = $(this);
    $(that).empty();
    $.each(storage, function(i, v) {
        $(that).append(v);
    });
})

The live demo:

Your page
localhost

Now this is more fun :) Everything should work now, try it. In the next lesson, Classes in jQuery (DOM), we'll show how to work with element classes using jQuery.


 

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

By downloading the following file, you agree to the license terms

Downloaded 3x (1.78 kB)
Application includes source codes in language JavaScript

 

Previous article
Replacing contents & cloning with jQuery (DOM)
All articles in this section
jQuery Basics
Skip article
(not recommended)
Classes in jQuery (DOM)
Article has been written for you by Honza Bittner
Avatar
User rating:
1 votes
Everything is possible.
Activities