🚨 Get Your Free NFT Certificate Mint by Completing the Web3 Exam! START NOW

Code has been added to clipboard!

jQuery .insertBefore(): Add Content Before Specified HTML Elements

Reading time 1 min
Published Jan 19, 2018
Updated Oct 1, 2019

jQuery insertBefore: Main Tips

  • The jQuery .insertBefore() method adds content before the specified HTML elements.
  • Differently from the .before() method, .insertBefore() requires new content parameter to precede the target elements.
  • To add content as last descendant of the element, use .prepend(). To add it as a last child, remember learning about jQuery .append() before.

Learn to Use .insertBefore()

The .insertBefore() jQuery command adds content before the indicated elements. The example below is set to add a header before the <div> element:

$("button").click(() => {
    $("<h1>Hello world!</h1>").insertBefore("div");

To use jQuery .insertBefore() method, you will need this syntax:


.insertBefore() jQuery syntax accepts two arguments:

  • content to insert.
  • target to specify before which elements will content be inserted. It can be specified by either using a selector, or defining an exact jQuery object, HTML string, element, or an element array.

Tip: use jQuery .insertAfter() method to add content after specified HTML elements.

Note: if you wish to add content as children of the element, learn about jQuery .prepend() and jQuery .append() before doing that.