jQuery prepend() Method - CodingTag
×


jQuery prepend()

1135

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

Related Topics:

jQuery insertAfter
jQuery insertBefore

jQuery prepend

Note:

To insert the content at the end, use append() jQuery method.

Syntax:

$(selector).prepend(content,function(index,html));

Parameter description:

  • content: This represents the contents which to be insert at the starting of the selected element. It can be either plain text or it may contain HTML tags. It is a mandatory parameter. Possible values for this parameter are:
  • 1 HTML elements

    2 DOM elements

    3 jQuery objects

  • function(index,html): This represents a function which used to return the content to insert. It is optional.
  • index: This parameter is used to get the current HTML of the selected element.

Example:

In this example we insert a new paragraph before the <h3> tag in the <div> 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>
.para1{
background:yellow;
padding:10px;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){
$text="<p class='para1'>This is the newly inserted paragraph before the heading.</p>";
$("div").prepend($text);
});
});
</script>
</head>
<body>

<h2> jQuery prepend() Method Example </h2>
<div>
<h3> This is heading. </h3>
</div>
<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