jQuery Append

While creating web applications, appending content into a HTML target on particular event is an interesting task. In a HTML container, we can add any content using jQuery append. The added content will be literally appended. That means, the existing content will be there followed by appended content.

jQuery_append

jQuery Append Functions

  • append()
  • appendTo()

These two functions are identical with their results but differs in syntax. Performance wise they differ but not significantly.

append is targetContainer.append(newContent) and appendTo is newContent.appendTo(targetContainer);

jQuery append()

targetContainer.append(newContent)

This function is invoked with the reference of any selector string. It contains a parameter to accept content to be appended to the target. While invoking jQuery append(), it will search for target HTML container with respect to the selector string. If match found, then content will be added as the last child of target HTML tags. For example,

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script language="javascript">
$( document ).ready(function() {
$(".message").append("Added using jQuery append()");
});
</script> 
<div class="message">Message: </div>

Output:

<div class="message">Message: Added using jQuery append()</div> 

jQuery appendTo()

newContent.appendTo(targetContainer);

targetContainer – inside which html container the new content is to be added.

newContent – is the new content chosen to be added. It can be a selector or html content.

Using jQuery appendTo() function, we can move existing element into a target container tag. And, we can also create new content to be appended with target. For example,

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script language="javascript">
$(document).ready(function() {
//example-1 moving the first occurring paragraph to the class message
$("p").appendTo($(".message"));

//example-2 append the given html content to class message
$("<p>new content appended</p>").appendTo($(".message"));
});
</script>
<p>moved paragraph tag appended with target div</p> 
<div class="message">Message: </div>

First existing paragraph tag, is moved into target div and added as its last child. And then new paragraph tag is created on the fly and added with existing content of the target.

Output after first appendTo call:

<div class="message">Message: <p>moved paragraph tag appended with target div</p></div>

Output after second appendTo call:

<div class="message">Message: <p>moved paragraph tag appended with target div</p><p>new content appended</p></div>

Download jQuery Append Source Code

This jQuery code tutorial was published on October 17, 2013.

↑ Back to Top