jQuery prepend() Method

jQuery prepend() method inserts content to the beginning of selected elements.

jQuery prepend() method and prependTo() method perform the same function. There is one major difference is in the syntax, placement of the content and target element.

Use the append() method to insert content to the end of selected elements.

Syntax

This syntax represent to the prepend() method

$(selector).prepend( content, function(index, html) );
Parameter Type Description
content htmlString
Element
Text
Array
jQuery
Required. HTML string, DOM element, text node, array of elements, or jQuery object to insert to the beginning of selected elements.
function(index, html) Function Optional. A function that returns an HTML string, DOM element, text node, array of elements, or jQuery object to insert to the beginning of selected elements.
  • index - Return the index position of the element in the set as an argument.
  • html - Returns the old HTML of the selected element.

Example

Here, in this example prepend() method apply on selected elements when click on button.

<!DOCTYPE html>
<html>
<head>
  <title>jQuery prepend() method</title>
  <script src="jquery-latest.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("div").prepend("<p>New text to the beginning of selected element.</p>");
      });
    });
  </script>
</head>
<body>
  <div>
    <p>First paragraph start here...</p>
  </div>
  <button>Click Me</button>
</body> 
</html>

Run it...   »