prepend()

The jQuery prepend() method is used to insert the specified content at the beginning (as a first child) of the selected elements. It is just the opposite of the jQuery append() method.

If you want to insert the content at the end of the selected elements, you should use the append method.

Syntax:

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

Parameters of jQuery prepend() method

Parameter Description
Content It is a mandatory parameter. It specifies the content which you want to insert. Its possible values are:
  • HTML elements
  • jQuery objects
  • DOM elements
Function (index, html) It is an optional parameter. It specifies a function that returns the content which is inserted.
  • Index:It is used to provide the index position of the element in the set.
  • Html: : It provides the current HTML of the selected element.

Example of jQuery prepend() method

Let's take an example to demonstrate the jQuery prepend() method.

snippet
<!DOCTYPE html>  
<html>  
<head>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  
<script>  
$(document).ready(function(){  
    $("#btn1").click(function(){  
        $("p").prepend("<b>Prepended text</b>. ");  
    });  
});  
</script>  
</head>  
<body>  
<p>This is the first paragraph.</p>  
<p>This is the second paragraph.</p>  
<button id="btn1">Prepend text</button>  
</body>  
</html>

Output:

This is the first paragraph.

This is the second paragraph.

jQuery prepend() example 2

snippet
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#btn1").click(function(){
        $("p").prepend("<b>Prepended text</b>. ");
    });
    $("#btn2").click(function(){
        $("ol").prepend("<li>Prepended item</li>");
    });
});
</script>
</head>
<body>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<ol>
  <li>Item no.1</li>
  <li>Item no.2</li>
  <li>Item no.3</li>
</ol>
<button id="btn1">Prepend text</button>
<button id="btn2">Prepend list item</button>
</body>
</html>

Output:

This is the first paragraph.

This is the second paragraph.

  1. Item no.1
  2. Item no.2
  3. Item no.3

jQuery prepend() example 3

snippet
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>prepend demo</title>
  <style>
  p {
    background: lightpink;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 <p>rookienerd.com</p>
<p>Guys! Welcome to the best tutorial site.</p>
 <script>
$( "p" ).prepend( "<b>Hello </b>" );
</script>
 </body>
</html>

Output:

Hello rookienerd.com

Hello Guys! Welcome to the best tutorial site.

Note
Here, "Hello" is the prepended text.
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +