jQuery How-to: Creating and Inserting New Element (Part 2)

By . Filed in Web Design

In our previous post, we started a discussion on how to create and insert new elements with the jQuery (and JavaScript) Append method. We’ve learned how to create and insert new elements to the body document.

In its basic form, the Append method inserts the new element as the last child or (technically) before the closing tag of a specified element. In certain cases, however, we might need to insert the new element at a more specific point. In this post, we will tackle this issue.

For demonstration purposes, we have prepared the following HTML unordered list structure, containing the id, list.

<ul id="list">
	<li>Ut enim ad minim veniam.</li>
	<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</li>
	<li>Duis aute irure dolor in reprehenderit.</li>
	<li>Sunt in culpa qui officia deserunt mollit.</li>
	<li>Excepteur sint occaecat cupidatat non proident.</li>
</ul>

Insert New Element as the First Child

In this first example, we will create a new element and insert it as the first child of a specified element (parent). As in our previous post, we will first look at how it is done purely with JavaScript and subsequently with jQuery.

The idea in the following example is we will create a new <li> and then insert it as the first child of the <ul>. So, let’s create a new element as well as the text inside it, like so.

var li 	= document.createElement('li'),
	txt = document.createTextNode('This is the text in new element.');

li.appendChild(txt);

To insert this element as the first child, we can use the JavaScript .insertBefore() function. This function allows us to insert an element before an existing element.

Now, we need to specify which parent to nest the new element inside. In this example, we specify the element by getting its ID attribute, like so:

ul 	= document.getElementById('list');

Then, we need to define which element to place the "new element" before. In our case, it would be the first child of the parent. In JavaScript, we can get the first child element with .firstChild function and we store it in a variable called firstChild.

var firstChild = ul.firstChild;

We then apply the function. First, we set the parent element with ul variable followed by .insertBefore() function, like so.

ul.insertBefore();

Inside the parentheses, we specify the new element followed by the reference element (the first child of the parent).

ul.insertBefore(li, firstChild);

This code above will insert the new li before the first child element. If we take a look at the browsers and inspect the element through the Developer Tool, we will get this result:

We see that our new element is now the first child of the <ul>.

Using jQuery

Alternatively, we can use jQuery. jQuery has a function called .prepend(). We can achieve the same result by writing it in this one way.

$('#list').prepend('<li>This is the text in new element. (with jQuery)</li>');

Insert New Element in Specific Point

Now, how about adding the new element at a more specific point, such as before or after the 3rd child – as opposed to first and last. Here’s how we do it in both JavaScript and jQuery.

We have created a new element from the previous example, like so:

var li 	= document.createElement('li'),
	txt = document.createTextNode('This is the text in new element.');
li.appendChild(txt);

We need to grab the list element. In JavaScript, we use .getElementsByTagName() to select element by their tag name.

var list = document.getElementsByTagName('li');

After that, we need to get the 3rd list element, which can be specified with its index number. The index number in JavaScript started from 0, thus the 3rd element would be 2 in the index. In the following code, we store this element in nthList variable.

var nthList = list[2];

Now, we can use .insertBefore() function to add the new element before the 3rd child of specified element:

ul.insertBefore(li, nthList);

If we view the browser, we will get:

To insert the new element after it, we can use .insertBefore() function along with .nextSibling(), which specifies the next element.

ul.insertBefore(li, nthList.nextSibling);

Contrary to the previous example, the following code will insert the new element after the 3rd child of the specified element.

Using jQuery

jQuery introduced .before() and .after() function to simplify the process. And, we can use jQuery .eq() function to target element upon their index.

Referring to our example above, we can do the same thing with:

$('li').eq(2).before('<li'>This is the text in new element. (with jQuery)</li>');

to add the new element before the 3rd child of specified element. Or, we can write it this way to insert after it.

$('li').eq(2).after('<li'>This is the text in new element. (with jQuery)</li>');

Conclusion

We have learned how to create and insert new elements with JavaScript and used jQuery functions to simplify the process (yet achieve the same result). It is now up to your choice to figure out which is more efficient to your case.

Hopefully, this session can be useful for you, paticularly for those who are just getting started with jQuery or JavaScript. If you have anything to ask, feel free to add it in the comment section below.

Useful Resources

Below are a few useful resources to dig into this subject further.

Author:

Thoriq has been dabbling in Web Design for 5 years and appreciates the giving nature of the web design community at large. He loves trying new things in CSS3 and HTML5. Apart from writing on hongkiat.com he also maintains creatiface.

Tags:

Advertisement