The before method

The before method adds text before the given element. There is also a insertBefore method that works in a similar way.

Syntax

Insert text before an element:

javascript$(selector).before(text);

This is how the text that will be returned by the custom function will be added before the selected elements:

javascript$(selector).before(function(number in set));

Another option for using the function, the second parameter specifies the old html value of the element:

javascript$(selector).before(function(number in set, html string));

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

Example

Let's insert some text before the given paragraph:

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

HTML the code will look like this:

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

Example

Let's insert text with tags before the given paragraph:

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

HTML the code will look like this:

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

Example

Let's put one paragraph above the other (that is, cut the paragraph from the old place and put it in the new one):

html<p id="p1">text1</p>
<p id="p2">text2</p>
javascript$('#p2').before('#p1');

HTML the code will look like this:

html<p id="p2">text2</p>
<p id="p1">text1</p>

See also