jQuery How-to: Creating and Inserting New Elements (Part 1)
In this post, we are going to take a look at how to create or insert new elements within DOM with the jQuery Append method.
Recommended Reading: JQuery: Creating And Inserting New Element – Part II
Insert New Element
Appending is a method of creating and inserting new element within a specified element, it technically inserts the new element right before the closing tag of that specified element – thus becoming its child element.
.createElement() function to create a new element. In the following example, we create a new
<div> element and store it in a variable named
var div = document.createElement('div');
By the time we define a new element with this function, it only creates the element, but it doesn’t insert the new element to the document. We need to call one function, that is
.appendChild() to insert that element. In the following example, we will insert this new
<div>, simply, in the body document.
var div = document.createElement('div'); document.body.appendChild(div);
If we inspect the document in Developer Tool, you should see that our div element has been inserted there, before the body closing tag.
Now, let’s see how we do the same thing with jQuery. jQuery makes manipulating document elements simpler. jQuery provides a function called
In the following example, we append a
<div> to body document.
Insert New Element with Text
To do so, we need to define the new element and the text. Since we will add text, we can create a paragraph element in this example.
var p = document.createElement('p'); // create new paragraph element
.createTextNode() function. In this example, we store the text value in a variable named
var p = document.createElement('p'), txt = document.createTextNode('This is the text in new element.');
At this point, we have two variables, which store the new element and the text respectively. However, they are still separated and can stand alone. To insert the text to the new element we have created, we can run the same
.appendChild() function, like so.
Then again, we run
.appendChild() to insert the element to the body document.
If we see it in the browser or through the Developer Tool, we get:
In jQuery, the process is simplified. Instead of separately defining two variables for the text and the new element, we can write them together with
.append() function, like so.
$('body').append('<p>This is the text in new element.<p>');
The above code essentially does the same thing, it will insert the the text with
<p> element to the body (before the body closing tag).
You can see that using jQuery with
This article is only the beginning. In the next part, we will see how to insert element in more advanced way. So, stay tuned!
If you have some questions upon our discussion in this post, feel free to add it in the comment box below.