jQuery Prepend – The Complete Guide with Lots of Examples

jQuery Prepend – The Complete Guide with Lots of Examples

The jQuery Prepend method prepends the content inside of every matched element (selector) i.e. it insert the specific content as the first child of the selector.
It is exactly opposite to the jQuery Append method and is very helpful in doing DOM Manipulation.

Syntax

$(selector).prepend( 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

There can be any number of content to add in a single prepend statement.
Let me show you how to Prepend some text to a div. I give this div an id as prependDiv.

<div id="prependDiv">Welcome</div>
Adding Single Content with jQuery Prepend
Welcome

$("#prependDiv").prepend("To YogiHosting ")

It will become:

<div id="prependDiv">To YogiHosting Welcome</div>
Adding 3 Contents with jQuery Prepend
Welcome

$("#prependDiv").prepend("To YogiHosting, ","Are you enjoying, ", " coding? ")

It will become:

<div id="prependDiv">To YogiHosting, Are you enjoying, coding? Welcome</div>

jQuery Prepend HTML

You can also Prepend HTML in a selector. Here I will prepend a paragraph to a div.

<div id="prependDiv">
    Welcome
</div>

To the above prependDiv div, I will prepend a paragraph element using jQuery Prepend method.

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

It will become.

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

jQuery Prepend to DOM

Using jQuery Prepend method, an element in the DOM is cut from its location and pasted as the first child of the selector.
Suppose there is an HTML:

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

I can cut the h4 element and make it the first child of the div having class as fullName:

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

This will make the HTML as:

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

jQuery Prepend Text

You can also Prepend any Text using the jQuery Prepend() method. Let’s see the following example:

<p>The President of United States </p>
$("p").prepend("Donald Trump Is ");

The above paragraph will become:

<p> Donald Trump Is The President of United States</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.