jQuery prependTo() Method - CodingTag
×


jQuery prependTo()

1021

  • This jQuery method is used to insert the given content at the starting of the selected HTML element means this method insert the specified content as the child element by the user before the beginning of the matched element.

Related Topics:

jQuery insertBefore
jQuery insertAfter

jQuery prependTo

Note:

prepend() and prependTo() both jQuery methods are used for same work but the only difference between these methods is in their syntax.

Syntax:

$(content).prependTo(selector);

Parameter description:

  • content: This represents the contents which to be insert at the starting of the selected elements. It is mandatory and must contain HTML tags. If the content is already exists on the webpage then it will be moved at the starting of the selected element.
  • selector: selector represents a jQuery selector that is used to select the HTML element.

Example:

In this example we insert a new <span> at the beginning of every <p> tag.

<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
.sp{
color:red;

}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){
$text="<span class='sp'>Welcome freinds!! </span>";
$($text).prependTo("p");
});
});
</script>
</head>
<body>

<h2> jQuery prependTo() method Example </h2>
<p> This is the paragraph 1 </p>
<p> This is the paragraph 2 </p>
<p> This is the paragraph 3 </p>
<p> This is the paragraph 4 </p>
<button> Click me! </button>
</body>
</html>

Output:

When you click the button,



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments