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

Lesson 2 - Inserting contents in jQuery (DOM)

In the previous lesson, Introduction to jQuery, we introduced the JavaScript jQuery library and created a simple web application in it. In today's tutorial, we're going to show how to insert new contents into the page using jQuery. We'll try different approaches with examples.

Let's start by creating an HTML file and a JS file.

We'll insert the basic structure into the JS file. Unlike to the previous lesson, we'll use the shorter syntax of the Document Ready event today.

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

Inserting contents into elements

Let's show how to place some content as a new child of an element which we select using a selector. We can insert new child element either as the last child at the end of other children or as the first child at the beginning. We have several methods available which we're going to showcase one by one.

These are html(), text(), append(), appendTo(), prepend(), and prependTo().

We'll create an HTML code as shown below. It's several divs, wrapped in another <div> with id="inserting".

<div id="inserting">
    <div class="one">
        <b>Lorem ipsum <i>dolor sit amet</i></b>, consectetur adipisicing <s>elit</s>, sed do eiusmod tempor <b>incididunt</b> ut <b>labore</b> et dolore <u>magna aliqua</u>. Ut enim ad <i>minim veniam</i>.
    </div>
    <div class="two"></div>
    <div class="three"></div>
    <div class="four"></div>
</div>

We can add some styles as well:

body {
   background: #eee;
   color: #3d3d3d;
   margin: 0px;
   font-family: 'Advent pro';
}

#inserting div {
   margin: 15px 0 15px 4%;
   padding: 2%;
   background: #fff;
   width: 40%;
   float: left;
}

#inserting .gray {
   background: #cacaca;
   width: 300px;
   padding: 20px;
   min-height: 100px;
}

#inserting .red {
   background: red;
   width: 80%;
   margin: 8%;
   padding: 2%;
}

The result in the browser:

Your page
localhost

html() and text()

These two methods set or get the contents of the whole element. The html() method works with HTML code and text() sets or gets text contents only.

Let's make an example. We'll select the first <div> in our code using the #inserting .one selector, this will be our content source. Therefore, we'll store it to a source variable.

let source = $('#inserting .one');

Now we can try the html() method. Let's try to get the HTML code of the source contents and set it as the HTML code of the second <div>. The second div's selector is #inserting .two.

let source = $('#inserting .one');
$('#inserting .two').html(source.html());

The result:

Your page
localhost

The contents of the first <div> has been copied, of course, to the second <div> even with the nested HTML elements, so the text emphasis was kept as well. Now let's try to do the same but with the text() method. We'll set the result as the contents of the third <div> (div.three).

let source = $('#inserting .one');
$('#inserting .two').html(source.html());
$('#inserting .three').text(source.text());

The result:

Your page
localhost

What we got is only the text contents of the element without any HTML elements, so without emphasis in our case. We can also combine these two methods, we can set the HTML contents of the source as the text of the fourth <div> (#inserting .four).

let source = $('#inserting .one');
$('#inserting .two').html(source.html());
$('#inserting .three').text(source.text());
$('#inserting .four').text(source.html());

The result:

Your page
localhost

Now this is interesting. We got the HTML code of the contents of the source element and set it as text contents of the fourth <div>. Except for the text, the HTML markup code is also visible. That's basically all we can do with these functions.

append() a appendTo()

You may have already guessed that the methods append an element to the contents of another. Both methods act very similarly, however, there's a significant difference between them.

  • a.append(b) - appends b to a
  • a.appendTo(b) - appends a to b

Now that we know what do these methods do, we can try them out on our example. Let's append "<b>Hi, I'm APPENDED</b>" to the #inserting .three div. We'll keep the contents of the previous example there as well.

let source = $('#inserting .one');
$('#inserting .two').html(source.html());
$('#inserting .three').text(source.text());
$('#inserting .four').text(source.html());

$('#inserting .three').append("<b>Hi, I'm APPENDED</b>");

The result:

Your page
localhost

Great, this works. Now let's do the same with appendTo(), however, this time we'll use cursive instead of bold text.

let source = $('#inserting .one');
$('#inserting .two').html(source.html());
$('#inserting .three').text(source.text());
$('#inserting .four').text(source.html());

$('#inserting .three').append("<b>Hi, I'm APPENDED</b>");
$("<i>Hi, I'm an APPENDEDTO</i>").appendTo('#inserting .three');

The result:

Your page
localhost

We can see that this works as well. Let's then append the #inserting .two <div> to the #inserting .three <div>.

let source = $('#inserting .one');
$('#inserting .two').html(source.html());
$('#inserting .three').text(source.text());
$('#inserting .four').text(source.html());

$('#inserting .three').append("<b>Hi, I'm APPENDED</b>");
$("<i>Hi, I'm an APPENDEDTO</i>").appendTo('#inserting .three');
$('#inserting .two').appendTo($('#inserting .three'));

The result:

Your page
localhost

The whole #inserting .three element was inserted inside. If we wanted to insert its contents only, the html() method might be helpful.

let source = $('#inserting .one');
$('#inserting .two').html(source.html());
$('#inserting .three').text(source.text());
$('#inserting .four').text(source.html());

$('#inserting .three').append("<b>Hi, I'm APPENDED</b>");
$("<i>Hi, I'm an APPENDEDTO</i>").appendTo('#inserting .three');
$($('#inserting .two').html()).appendTo($('#inserting .three'));

The result:

Your page
localhost

However, we must keep in mind that this way the original #inserting .two remains in the page as well.

prepend() a prependTo()

The prepend() method does the same as append(), the difference is that the element is inserted before the contents. As an example we can insert e.g. #inserting .four before the contents of #inserting .one.

$('#inserting .one').prepend($('#inserting .four'));

The result:

Your page
localhost

Inserting around an element

Now let's comment out the append and prepend code in our JavaScript so that our showcase isn't too messy. jQuery also offers functions that inserts contents around our element, not inside. These are functions are after(), insertAfter(), before(), and insertBefore().

after() a insertAfter()

The difference between after() and insertAfter() is as follows:

  • a.after(b) - Inserts b after a. The a element is the target, b is the element being inserted
  • a.insertAfter(b) - Inserts a after b. The a element is being inserted, b is the target

Let's try to add a new <div> after the #inserting .one <div> which will contain "Hi, I'm being inserted by After". We'll also assign id="by_after" to the new <div> because we're going to work with it further on.

$('#inserting .one').after("<div id='by_after'>Hi, I'm being inserted by <b>.after()</b></div>");

The result:

Your page
localhost

Great, it works. Our <div> was inserted right after #inserting .one. Now let's try to insert our new <div> with id="by_after" after #inserting .two.

$('#by_after').insertAfter($('#inserting .two'));

The result:

Your page
localhost

before() a insertBefore()

These two methods work similarly to the already mentioned after() and insertAfter() methods, but insert content before an element. But let's try something different. We're going to create a <div> with id="by_before" and place it before our <div> with #by_after.

$('#by_after').before("<div id='by_before'>Hi, I'm being placed by <b>.before()</b></div>");

It works. This is how it should look:

Your page
localhost

Wrapping an element

Okay, but what if we want to wrap our element in another? We have several other methods that do this for us. These are wrap(), unwrap(), wrapAll(), and wrapInner().

As a parameter of all these methods, we can pass a new element or some already existing one. If we pass an already existing element, this element will stay in the page and our element(s) will be wrapped by its copies together with all it contains.

wrap()

The wrap() method wraps our element in another element, there can even be more of them. The usage is very simple again. Let's wrap, for example, the #by_before** <div> in an <article> element and wrap that in a <section> element.

$('#by_before').wrap('<section><article></article></section>');

The result:

Your page
localhost

If you want to wrap something in multiple elements, you can specify them like this. We can try out wrapping with more elements as well:

$('#by_before').wrap( "<div><div><p><em><b></b></em></p></div></div>" );

unwrap()

The unwrap() method is the opposite of wrap(). It removes the elements wrapping our element(s). It's written the same way as wrap(). Let's remove the <article> around our #by_before <div>.

$('#by_before').unwrap('<article></article>');

Voila, the article around is removed.

The result:

Your page
localhost

wrapAll()

The wrapAll() method finds all elements which match a given selector and wrap them together. It joins all the results and place them into a new common parent.

Let's create div.gray in #inserting and try out something! What about wrapping e.g. #by_after and #inserting .four?

$('#by_after, #inserting .four').wrapAll($('.gray'));

The result:

Your page
localhost

The original .gray (try to put some text in it) remains and its copy is used to wrap our selection.

wrapInner()

As the last one, there's wrapInner() which, as you may have already guessed, wraps the inner contents of an element. In other words, it creates a new child in which the rest of the contents is wrapped.

Let's try to create a child for #by_after as div.red which will set a red background and some margin.

$('#by_after').wrapInner('<div class="red"></div>');

The result:

Your page
localhost

That's all for inserting content and for today. In the next lesson, Replacing contents & cloning with jQuery (DOM), we'll talk about replacing contents and cloning.


 

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 (2.01 kB)
Application includes source codes in language JavaScript

 

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