English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

jQuery prependTo() Method

jQuery HTML/CSS Methods

The prependTo() method inserts HTML elements at the beginning of each selected element (as the first child).

To insert an HTML element at the end of the selected element, useappendTo()method.

Thisprepend()and performs the same task as the prependTo() method. The main difference is in syntax:

  • Usingprepend()The selector expression before the method is the container into which the content is inserted

  • UsingprependTo()The content is specified as a selector expression before the method and is inserted into the target container.

//prepend()
$("#btnpre").click(function(){
//This method inserts the specified content at the beginning (still inside) of the selected element.
  $("div").prepend("<p>Hello prepend!</p>");
});
//prependTo()
$("#btnpreto").click(function(){
//The prependTo() method inserts the specified content at the beginning of the selected element (still located inside).
  $("<p>Hello prependTo!</p>").prependTo("div");
});

Syntax:

$(content).prependTo(selector)

Instance

Add a <b> element at the beginning of all paragraphs:

$("button").click(function(){
  $("<b>Hello world</b>").prependTo("p");
});
Test and see‹/›

Use the prependTo() method to insert an existing element at the beginning of each selected element:

$("button").click(function(){
  $("h1").prependTo("p");
});
Test and see‹/›

Parameter value

ParameterDescription
contentSpecify the content to be inserted (must contain HTML tags)

Possible values:

  • HTML element

  • DOM element

  • jQuery object

selectorThe selected element will be inserted at the beginning of the element specified by this parameter

jQuery HTML/CSS Methods