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.

Learn jQuery
Introduction
Selectors
Events
Event Methods
Download
Callback
Chaining
Get and Set
Add Element
Remove Element
Traverse
Parent
Children
Sibling Traverse
Filtering
jQuery AJAX
Effects
Show and Hide
Fade Effect
Slide Effect
Animate Effect
Manipulate CSS
Width and Height
.addClass()
.after()
.animate()
.append()
.appendTo()
.attr()
.before()
.bind() (deprecated)
.blur()
.change()
.click()
.clone()
.css()
.dblclick()
.delay()
.delegate() and .undelegate() (deprecated)
.detach()
.empty()
.end()
.error() (deprecated)
.fadeIn()
.fadeOut()
.fadeTo()
.fadeToggle()
.finish()
.focus()
.focusIn()
.focusOut()
.hasClass()
.height()
.hide()
.hover()
.html()
.innerHeight()
.innerWidth()
.insertAfter()
.insertBefore()
.keypress()
.keyup()
.live() and .die() (deprecated)
.load() (deprecated)
.mousedown()
.mouseenter()
.mouseleave()
.mousemove()
.mouseout()
.mouseover()
.mouseup()
.off()
.offset()
.offsetParent()
.on()
.one()
.outerHeight()
.outerWidth()
.position()
.prepend()
.prependTo()
.prop()
.proxy()
.queue()
.ready()
.remove()
.removeAttr()
.removeClass()
.removeProp()
.replaceAll()
.replaceWith()
.resize()
.scroll()
.scrollLeft()
.scrollTop()
.show()
.slideDown()
.slideToggle()
.slideUp()
.stop()
.submit()
.text()
.toggle()
.toggleClass()
.trigger()
.triggerHandler()
.unbind() (deprecated)
.unload() (deprecated)
.unwrap()
.val()
.width()
.wrap()
Event Properties
event.currentTarget
event.preventDefault()
event.relatedTarget
event.stopImmediatePropagation()
event.stopPropagation()
event.target
event.timeStamp
event.type
event.which
jQuery .find()
jQuery .keydown()
jQuery.noConflict()
pageY and pageX