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 Manipulations.
$(selector).prepend( content [, content ] [, content ] [, content ]..... )
Parameter | Description |
---|---|
Content | Required. Specifies the content to insert
Possible values:
|
[, content ] | Optional. Specifies the content to insert
Possible values:
|
There can be any number of contents 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>
$("#prependDiv").prepend("To YogiHosting ")
It will become:
<div id="prependDiv">To YogiHosting Welcome</div>
$("#prependDiv").prepend("To YogiHosting, ","Are you enjoying, ", " coding?")
It will become:
<div id="prependDiv">To YogiHosting, Are you enjoying, coding? Welcome</div>
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>
Using the jQuery Prepend method, an element in the DOM is cut from it’s 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>
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>
Check the download codes link: