jQuery prepend() with Example

In this tutorial, I will explain about .prepend() method in jQuery.

jQuery prepend() method is used to insert the specified content at the beginning of the selected element. It is an inbuilt method in jQuery.

If we want to insert our content at the end of the selected elements, then we want to use jQuery .append() method.

Syntax

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

Parameters of JQUERY prepend() method

This .prepend() method accepts two parameters,

Content

 It is required parameter which is used to specify the content need to be inserted. The possible values which to be inserted are:

  1. DOM Elements
  2. HTML Elements
  3. jQuery Objects
  4. Text

Function( index, html)

It is an optional parameter. It is used to specify a function that returns the content which is inserted.

  1. index – It indicates the index position of the element in the set.
  2. html – It indicates the current HTML of selected element.

Example 1

<html>
<head>
    <title>Jquery</title>
   https://code.jquery.com/jquery-3.4.1.min.js
</head>
<body>
    <h1> Everybody, what's up!</h1>
</body>
</html>

When I run this above code, I get an output of

Output of above code

Now I’m going to use the jQuery .prepend() method to insert “Hello ” word at the beginning of “Everybody, what’s up!”.

<html>
<head>
    <title>Jquery</title>
   https://code.jquery.com/jquery-3.4.1.min.js
</head>
<body>
    <h1> Everybody, what's up!</h1>
    
    <script type="text/javascript">
       
       $(document).ready(function(){
           
         $("h1").prepend("Hello ");
           
       });
    </script>
   
</body>
</html>

Output:

Output of above jQuery .prepend() method

Example 2

Before using jQuery .prepend() method,

<html>
<head>
    <title>Jquery</title>
   https://code.jquery.com/jquery-3.4.1.min.js
</head>
<body>
    <p>I'm just a paragraph</p>   
</body>
</html>

Output:

Now I want to insert the bold tag before the paragraph tag, how can we do this, see below

<html>
<head>
    <title>Jquery</title>
   https://code.jquery.com/jquery-3.4.1.min.js
</head>
<body>
    <p>I'm just a paragraph</p>
    
    <script type="text/javascript">
       
       $(document).ready(function(){
           
        $("p").prepend("<b>I'm bold inserted before paragraph : </b>");
           
       });
    </script>
   
</body>
</html>

Output:

If you like this article, please follow my blog via email

Leave a Comment

Your email address will not be published. Required fields are marked *