jQuery Append – The Complete Guide with Lots of Examples

jQuery Append – The Complete Guide with Lots of Examples

The jQuery Append method appends the content inside of every matched element. It is very helpful in doing DOM Manipulation.

Syntax

$(selector).append( content [, content ] [, content ] [, content ]..... )

Parameter Description
Content Required. Specifies the content to insert

    Possible values:

  • HTML elements
  • jQuery objects
  • DOM elements
  • Text
[, content ] Optional. Specifies the content to insert

    Possible values:

  • HTML elements
  • jQuery objects
  • DOM elements
  • Text

You can use any number of content to add in a single append statement.
Let us add content to a div having id myDiv.

<div id="myDiv">Welcome</div>
Adding a Single Content with jQuery Append
Welcome

$("#myDiv").append(" to YogiHosting")

It will become:

<div id="myDiv">Welcome to YogiHosting.</div>
Adding 3 Contents with jQuery Append
Welcome

$("#myDiv").append(" to YogiHosting."," Are you enjoying", " coding?")

It will become:

<div id="myDiv">Welcome to YogiHosting. Are you enjoying coding?</div>

jQuery Append HTML

Now I will show how to append an HTML element to a div.

<div id="myDiv">
    Welecome
</div>

To the above div element append a paragraph element using jQuery Append.

$("#myDiv").append("<p>to YogiHosting. Are you enjoying coding?</p>")

It will become.

<div id="myDiv">
    Welecome
    <p>to YogiHosting. Are you enjoying coding?</p>
</div>

jQuery Append to DOM

Using jQuery Append method, an element in the DOM can be shifted from one location to another.
Consider the following HTML:

<h4>USA</h4>
<div class="fullName">
    <p>United</p>
    <p>States</p>
    <p>America</p>
</div>

I can move the h4 element inside of div having class as fullName:

$(".fullName").append($("h4")); 

This will make the HTML as:

<div class="fullName">
    <p>United</p>
    <p>States</p>
    <p>America</p>
    <h4>USA</h4>
</div>

jQuery Append Text

You can also append any text using the jQuery Append method. Let us append a text to the HTML paragraph:

<p>The President of United States is: </p>
$("p").append("Donald Trump");

The above paragraph will become:

<p>The President of United States is:  Donald Trump</p>

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on “WordPress, SEO, jQuery, HTML” and more.