jQuery prepend()

The jQuery prepend() inserts content at the beginning of the selected elements.

Syntax:

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

Content:

  • Content is a compulsory parameter of the jQuery prepend() method, as it specifies the content to insert at the beginning of the selected element.
  • It can accept the following values: HTML elements, jQuery objects, and DOM elements.

Function:

  • It is an optional parameter.
  • The function parameter is used to return the inserted content.

Index:

  • The index is an argument passed within the function.
  • It is used to give an index position to an element in the set.

Html:

  • It provides the current HTML of the selected element.

Example1:

<!DOCTYPE html>
<html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").prepend("Hello! ");
});
});
</script>
</head>
<body>
<p>How are you?</p>
<button>Click me</button>
</body>
</html>

Example2:

<!DOCTYPE html>
<html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("ol").prepend("<li>Brain</li>");
});
});
</script>
</head>
<body>
<p>Do you have?</p>
<ol>
<li>Ear</li>
<li>Eyes</li>
<li>Nose</li>
</ol>
<button>Click me</button>
</body>
</html>