Black friday

Save big!

All courses under $5 - for a limited time!

Code has been added to clipboard!

How jQuery .before() Differs From .insertBefore() and How to Use It

Reading time 1 min
Published Jan 18, 2018
Updated Oct 2, 2019

jQuery before: Main Tips

  • jQuery .before() inserts content before the selected elements. To add it after elements, use .after().
  • While it achieves the same goal as .insertBefore, jQuery .before() uses different syntax.

Usage and Syntax of before

The .before jQuery method inserts additional content before the defined element (one or multiple). In the example below, extra text is displayed before the heading:

Example
$("button").click(() => {
    $("h1").before("<p>Get ready!</p>");
});

The syntax for jQuery .before() is as follows:

$(selector).before(content);

  • The content can specify either exact content or a function that returns it.
  • In jQuery before, selector specifies the elements the new elements will be added to.

Note: the content to insert might have a value of a jQuery object, HTML string, DOM element, a text node, or an array of either elements or nodes.