Lesson 3 - Replacing contents & cloning with jQuery (DOM)

JavaScript jQuery basics Replacing contents & cloning with jQuery (DOM)

In the previous lesson, Inserting contents in jQuery (DOM), we learned different ways to insert contents using the jQuery JavaScript library. In today's tutorial, we're going to learn how to replace contents and try different approaches with examples. Now let's look at cloning.

Let's start with creating an HTML file and a JS file again. We'll insert the basic structure to the JS file with the Document Ready event:

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

Content replacement

The following methods replace existing elements with others. We can use this, even though it might not seem so, to reduce the size of our code.

The methods are called replaceAll() and replaceWith(). There's the following difference between them:

  • a.replaceAll(b) - replaces b with the a element
  • a.replaceWith(b) - replaces a with the b element

It's important to realize the difference between the methods from the previous lesson, such as html() and text(), and between the methods replaceAll()/replaceWith(). These don't replace only the contents of an element, but the element itself. That's much more fun, isn't it? :)

Let's have a short showcase and introduce different ways of usage. We'll create an HTML file such as this:

<p>I want</p>
<p>to greet</p>
<p>Penny</p>
<p>!</p>

Let's also edit the CSS where we'll add styles for the <p> paragraphs and <div> elements.

p {
        background: #ed1c24;
        border: 2px solid #7f0011;
        padding: 5px 10px;
        margin: 10px;
        display: table;
        color: #ededed;
}

div {
        background: #0080C0;
        border: 2px solid #004080;
        padding: 5px 10px;
        margin: 10px;
        display: table;
        color: #ededed;
}

Our document looks like this so far:

Your page
localhost

We'll create several examples of content replacement.

Example #1

First, we'll simply replace our paragraphs with <div> elements which will contain the text "Replaced".

It's very simple, let's show the JavaScript code to do that:

$('p').replaceWith('<div> Replaced </div>');

The result:

Your page
localhost

Great, everything works just fine. Let's also have a look at how to use the second approach, replaceAll().

$('<div> Replaced </div>').replaceAll('p');

Of course, the result will be the same as in the previous example:

Your page
localhost

Let's move to more interesting examples then.

Example #2

Let's replace our paragraphs with divs containing the text "Knock", where the last one will contain "Penny!". This quote comes from The Big Bang Theory series where one of the main protagonists knocks on the door of his neighbor this way. You probably already know how to do this.

$('p').replaceWith('<div> Knock </div>');
$('div:last').replaceWith('<div> Penny! </div> ');

The code works just like we need but it's not very good. Although, it doesn't matter now that we're replacing one of the elements twice, if we tried this with a few hundreds of elements e.g. in some game or app, we'd just waste the performance unnecessarily.

Your page
localhost

Let's show how to solve the problem better. We'll use the not() method which selects elements that don't match a given selector.

First, we'll select the paragraphs which aren't last. We can use not('p:last') here:

$('p').not('p:last').replaceWith('<div> Knock </div>');

And right after that, we'll add a replacement of the last paragraph with <div> with the text of "Penny!".

$('p:last').replaceWith('<div> Penny! </div>');

The result:

Your page
localhost

It's simple and better for sure :)

Example #3

Let's show how we can change only the tag of the element and keep its content as it is. The each() method used on all the paragraphs could be useful here.

We'll call the each() method on the selected paragraphs, executing the callback function for each paragraph. In the function, we'll declare a content variable and store the current content of the element there. Then, we'll rewrite the element.

$('p').each(function() {
        let content = $(this).html();
        $(this).replaceWith('<div>' + content + '</div>');
});

The result:

Your page
localhost

It's all pretty simple. Let's do the same example in which the elements will be replaced when clicked. We'll just replace each() with on('click'). Everything else will stay the same. Let's keep the previous code and change the <div> to a <p> paragraph again when clicked.

$('div').on('click', function() {
        let content = $(this).html();
        $(this).replaceWith('<p>' + content + '</p>');
});

The live demo in a browser:

Your page
localhost

Cloning

In jQuery, there's also a method for cloning, i.e. copying - clone(). Let's show how it works. We simply add .clone() after our selector and the element will be copied, but not present in the page yet!

We'll create a new content in the HTML part. We can also comment out the previous code. Let's create the following example:

<b>Hello</b>

In a browser, it looks as follows so far:

Your page
localhost

Example #4

Now let's try to clone the text and then insert it after the original one.

$('b').clone().insertAfter('b');

The result:

Your page
localhost

It works. The clone() method only copies the element (similarly to pressing Ctrl + C) but doesn't insert anything yet. We already know the methods to insert elements with from the previous lesson - Inserting contents in jQuery (DOM).

Example #5

Let's add a paragraph into our HTML code as well:

<b>Hello</b>
<p>, how are you?</p>

Now we'll clone the bold text and insert it to the beginning of this paragraph. We'll use the prependTo() function to do it:

$('b').clone().prependTo("p");

The result:

Your page
localhost

Example #6

As next, we'll have a look at how to clone a paragraph and insert it after ours. We'll use the insertAfter() method to help us.

$('p').clone().insertAfter('p');

The result:

Your page
localhost

We can see that it's very simple.

Example #7

Let's show how to copy the paragraph, insert it after the paragraph, and then replace it with a <div> element while keeping its contents. This all will happen when the paragraph is clicked.

We can proceed e.g. this way:

$('p').on('click', function() {
        let content = $(this).html();
        $(this).clone().insertAfter($(this));
        $('p:last').replaceWith('<div>' + $('b').text() + content + '</div>')
});

The live demo:

Your page
localhost

Example #8

As the last one, we'll have a look at cloning a <div> element with the "Boo!" text in it. We'll create this element and comment out the previous HTML code.

<div> Boo! </div>

We'll bind the on('click') event to the element and clone it each time it's clicked.

$('div').on('click', function() {
        $(this).clone().insertAfter($(this));
});

The live demo:

Your page
localhost

Let's test it. When we click on the first <div>, everything works fine. But we can't click on the other ones. It's because the event attached to the element didn't clone with it. We can put this right simply, we'll just pass true as the parameter of the clone() method.

$('div').on('click', function() {
        $(this).clone(true).insertAfter($(this));
});

Now everything works:

Your page
localhost

That's all for today's lesson. In the next lesson, Removing contents in jQuery (DOM), we'll focus on removing elements using jQuery :)


 

 

Article has been written for you by Honza Bittner
Avatar
Do you like this article?
1 votes
Everything is possible.
Thumbnail
All articles in this section
jQuery basics
Activities (2)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!