jQuery prepend()

prepend content to one or multiple elements with prepend()

The jQuery prepend() method adds content at the beginning of any element in your page. The prepend() method can inserts content to a single element or to multiple elements.

Prepend content to a single element

In this tutorial, we will use a button that will add a new "li" element at the beginning of the "ul" list below each time the button is clicked.

Example:

  • Element 1
  • Element 2
  • Element 3
<ul>
	<li>Element 1</li>
	<li>Element 2</li>
	<li>Element 3</li>
</ul>

<input type="button" id="button" value="Add Element" />

When the element with the id "button" is clicked, the prepend() method will add a new "li" element at the beginning of the "ul" element.

<script type="text/javascript">

$('#button').click(function(){

	$('ul').prepend('<li>New element</li>');

});

</script>

Append content to several elements

You can use the prepend() method to insert content into multiple elements at the same time.

In this example, we will use a button that will add some text at the beginning of each "div" each time the button is clicked.

Div 1
Div 2
Div 3

This button will prepend new text in each "div"

<div>Div 1</div>
<div>Div 2</div>
<div>Div 3</div>

<input type="button" id="button" value="Add Element" />
<script type="text/javascript">

$('#button').click(function(){

	$('div').prepend('* new element * ');
});

</script>