prepend() Method - Javascript jQuery Method and Property

Javascript examples for jQuery Method and Property:prepend

Description

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

Syntax

ParameterRequire Description
content Required.HTML elements/jQuery objects/DOM elements content to insert
function(index,html) Optional.function that returns the content to insert
  • index - the index position of the element in the set
  • html - the current HTML of the selected element

The following code shows how to Insert content at the beginning of all <p> elements:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("<span>Hello World! </span>").prependTo("p");
    });//from  w w  w  .  j  ava  2  s.  c  o  m
});
</script>
</head>
<body>

<button>Insert span element at the beginning of each p element</button>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

</body>
</html>

Related Tutorials