The prepend method

The prepend method adds text to the beginning of an element. There is also a prependTo method that works in a similar way.

Syntax

Insert text at the beginning of an element:

javascript$(selector).prepend(text);

You can add text to the beginning of the selected elements, which will be returned by a custom function. The function is called separately for each of the selected elements. When called, it is passed the following parameters: the position of the element in the set, the current content of the element:

javascript$(selector).prepend(function(number in set, current element contents));

The content can also be not only plain text, but also a DOM element or jQuery object. In this case, these elements will move from their position in the HTML code.

Example

Let's insert text at the beginning of the given paragraph:

html<p id="test">text</p>
javascript$('#test').prepend('!!!');

HTML the code will look like this:

html<p id="test">!!!text</p>

Example

Let's insert text with tags at the beginning of the given paragraph:

html<p id="test">text</p>
javascript$('#test').prepend('<b>!!!</b>');

HTML the code will look like this:

html<p id="test"><b>!!!</b>text</p>

Example

Let's find all the paragraphs and put the serial number in the set at the beginning of each of them:

html<p>text</p>
<p>text</p>
<p>text</p>
<p>text</p>
<p>text</p>
javascript$('p').prepend(function(index, text) {
  return index;
});

HTML the code will look like this:

html<p>0text</p>
<p>1text</p>
<p>2text</p>
<p>3text</p>
<p>4text</p>

See also