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.

Latest Udacity Coupon Found:

Verified STAFF PICK

75% OFF COURSES

Udacity Black Friday Offer

The best time to save on Udacity courses is now - follow this coupon to access a 75% Udacity Black Friday discount & enjoy learning at a very low cost!

Expiration date: 28/01/2021
3176 People Used
Only 97 Left
Rating
5.0