jQuery .before() Method

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
DOM methods

What You’ll Learn

The .before() method inserts content immediately before each matched element as a sibling. This tutorial covers HTML strings, text nodes, DOM elements, jQuery objects, multiple arguments, and the callback form since 1.4, comparisons with .after(), .insertBefore(), and .prepend(), the official jQuery demos, and five practical try-it examples.

01

.before()

Prev sibling

02

HTML

Strings

03

DOM

Move nodes

04

Callback

Since 1.4

05

vs .after()

Sibling pair

06

Since 1.0

Core API

Introduction

Section headings, field labels, breadcrumb prefixes, and intro paragraphs often need to appear right above an existing element — not inside it. When content should sit as the previous sibling before a matched node, jQuery provides .before().

Available since jQuery 1.0, .before() is the mirror of .after(). Where .after() inserts content below the element, .before() inserts it above. You can pass HTML strings, text nodes, DOM elements, jQuery objects, multiple arguments, or a callback function (since 1.4).

.before() and .insertBefore() perform the same task with reversed syntax. Use .prepend() when content belongs inside the element. Browse the jQuery DOM hub for related manipulation methods.

Understanding the .before() Method

.before( content [, content ] ) inserts content immediately before each matched element in the DOM tree. The matched element itself is unchanged; new nodes appear as its preceding siblings. The return value is the same jQuery collection (for chaining).

When inserting an element already in the document before a single target, jQuery moves it rather than copying it. Since jQuery 1.4, the callback form .before( function( index ) ) runs once per matched element; return content to insert before that element.

💡
Beginner Tip

$(".inner").before(" Test ") adds “ Test ” before every .inner element — the official jQuery demo shows text appearing above “Hello” and “Goodbye”, not inside them.

📝 Syntax

jQuery .before() supports three forms:

Insert before — since 1.0

jQuery
.before( content [, content ] )
  • content — HTML string, DOM element, text node, array, or jQuery object.
  • Multiple arguments are inserted in order before each matched element.

Insert with callback — since 1.4

jQuery
.before( function( index [, html ] ) {
  // return content to insert; `this` is the current element
} )

Official before patterns

jQuery
$( "p" ).before( " Hello " );

⚡ Quick Reference

GoalCode
Insert HTML before element$("#section").before("<hr>")
Insert text node before$("p").before(document.createTextNode("Hi"))
Move existing element above$("#title").before($("#banner"))
Insert with callback$("p").before(function(){ return "<b>"+this.className+"</b>"; })
Insert below instead$("#section").after("<hr>")
Reversed syntax$("<hr>").insertBefore("#section")

📋 .before() vs .after() vs .insertBefore() vs .prepend()

Four related insertion APIs — pick the right position and syntax.

.before()
prev sibling

Insert content immediately before matched elements — anchor first: $(target).before(content)

.after()
next sibling

Insert content immediately after matched elements

.insertBefore()
same task

Insert before target — content first: $(content).insertBefore(target)

.prepend()
first child

Insert content inside matched elements as the first child

Examples Gallery

Examples 1–3 follow the official jQuery API documentation. Examples 4–5 cover the callback form and multiple-argument insertion from the docs. Use DevTools or the Try-it links to run each snippet in the browser.

📚 Getting Started

Official jQuery demos for HTML strings, text nodes, and existing elements.

Example 1 — Official Demo: Insert HTML Before Paragraphs

Insert “ Hello ” immediately before every paragraph.

jQuery
$( "p" ).before( " Hello " );
Try It Yourself

How It Works

jQuery inserts the string as the previous sibling before each matched element. The paragraph content is unchanged; the new text sits outside and above the opening tag. Avoid untrusted HTML strings to prevent XSS.

Example 2 — Official Demo: Insert a Text Node Before

Insert plain text with document.createTextNode() instead of an HTML string.

jQuery
$( "p" ).before( document.createTextNode( "Hello" ) );
Try It Yourself

How It Works

Text nodes bypass HTML parsing. The text appears immediately before each paragraph as a sibling node, exactly like the HTML string version but without interpreting tags.

📈 Practical Patterns

Moving elements, callback insertion, and multiple-argument sibling insertion.

Example 3 — Official Demo: Insert a jQuery Object Before

Insert an existing <b> element before paragraphs — jQuery moves it from its original location.

jQuery
$( "p" ).before( $( "b" ) );

// <b>Hello</b> moves to precede each <p>
// (cloned for all but last target if multiple matches)
Try It Yourself

How It Works

Inserting an existing DOM node before one target moves it to precede that element. With multiple targets, clones are created for all but the last match — same move-or-clone rules as .append() and .prepend().

Example 4 — Insert Before With Callback Function

Generate unique content before each paragraph using the callback form (since 1.4) — official jQuery pattern.

jQuery
$( "p" ).before( function() {
  return "<b>" + this.className + "</b>";
});
Try It Yourself

How It Works

The callback receives the index (and optionally old HTML since 1.10). Return a string, DOM node, or jQuery object to insert before the current element. Inside the function, this refers to the DOM element being processed.

Example 5 — Multiple Arguments Before First Paragraph

Pass several DOM elements and HTML strings in one call — official jQuery multi-argument pattern.

jQuery
var $newdiv1 = $( "<div class='note'>Note</div>" ),
    newdiv2 = document.createElement( "div" ),
    existingdiv1 = document.getElementById( "foo" );

newdiv2.textContent = "Created with createElement";

$( "p" ).first().before( $newdiv1, [ newdiv2, existingdiv1 ] );
Try It Yourself

How It Works

jQuery accepts arrays of nodes alongside individual arguments. Each item is inserted in order before the first paragraph. Existing elements move to the new location; newly created nodes become preceding siblings. Useful for inserting a header block, label, and icon row in one call.

🚀 Common Use Cases

  • Section headings — insert an <h2> or label immediately before a content block.
  • Form field labels — add helper text or required markers above input wrappers.
  • Breadcrumb prefixes — prepend navigation links as siblings before page titles.
  • Horizontal rules — add <hr> separators before new sections.
  • Relocate elements — move an existing heading or banner to precede a container.
  • Dynamic labels — use the callback form to insert badges showing each element’s class name.

🧠 How .before() Inserts Content

1

Match anchor elements

jQuery collection points at elements that will stay in place.

Select
2

Parse or accept content

HTML strings parsed; DOM nodes and jQuery objects inserted directly.

Content
3

Insert as previous sibling

Content placed immediately before each matched element in the parent.

Before
4

Return jQuery collection

Same anchor collection since jQuery 1.9 — ready for chaining.

📝 Notes

  • Available since jQuery 1.0 — callback form added in jQuery 1.4.
  • Inserts as the previous sibling; use .after() for the next sibling.
  • Matched elements are unchanged — content goes outside, not inside.
  • Inserting before a single target moves existing nodes; multiple targets clone except last.
  • Do not pass HTML strings from untrusted user input — XSS risk.
  • .prepend() inserts inside as first child; .before() inserts as sibling above.
  • Since jQuery 1.9, .before() always returns the original matched set.
  • Multiple arguments supported: .before(a, b, c).

Browser Support

.before() has been part of jQuery since 1.0+, with the callback form since 1.4+. It relies on standard DOM insertBefore operations on the parent node. Works in all browsers supported by your jQuery build — IE6+ through modern evergreen browsers in legacy jQuery versions, and all current browsers in jQuery 3.x and 4.x.

jQuery 1.0+

jQuery .before()

Universal sibling insertion API across jQuery 1.x, 2.x, 3.x, and 4.x. No browser-specific polyfills required — jQuery normalizes previous-sibling insertion. Pair with .after() for above/below sibling patterns.

100% With jQuery loaded
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
.before() Universal

Bottom line: Default choice for inserting content immediately before matched elements.

Conclusion

The jQuery .before() method inserts content as the previous sibling before each matched element. Pass HTML strings, text nodes, DOM elements, jQuery objects, multiple arguments, or a callback function — exactly as the official jQuery demos demonstrate.

Use .after() when content belongs below the element, and .insertBefore() when content-first syntax reads better. For content inside a container, use .prepend() or .append() instead. Next up: duplicating elements with .clone().

💡 Best Practices

✅ Do

  • Use .before() for headings, labels, and prefixes above an element
  • Create elements with .text() for safe dynamic label text
  • Use the callback form for per-element prefixes or class-name badges
  • Prefer .insertBefore() when building content before choosing the anchor
  • Check whether content belongs inside (.prepend) or outside (.before)

❌ Don’t

  • Use .before() when content should be a child inside the element
  • Pass untrusted HTML strings to .before() (XSS risk)
  • Confuse .before() with .prepend() (sibling vs child)
  • Assume inserting always clones — single target moves existing nodes
  • Call .before() on elements without a parent (no effect since 1.9)

Key Takeaways

Knowledge Unlocked

Six things to remember about .before()

The insert-above-sibling API — previous sibling insertion made easy.

6
Core concepts
<> 02

HTML

Or DOM

Content
03

vs after

Next sibling

Compare
fn 04

Callback

Since 1.4

Dynamic
05

vs prepend

Inside

Scope
1.9 06

Returns

Original set

Chain

❓ Frequently Asked Questions

.before() inserts the specified content immediately before each element in the matched set — as a sibling, not inside the element. It accepts HTML strings, DOM elements, text nodes, arrays, jQuery objects, multiple arguments, or a callback function (since 1.4). Returns the same jQuery collection for chaining. Available since jQuery 1.0.
.before() inserts content as the previous sibling before each matched element. .after() inserts content as the next sibling after each matched element. Both operate outside the matched element; neither adds children inside it.
Both insert content before target elements. With .before(), the matched element is the anchor: $('p').before('<hr>'). With .insertBefore(), the content comes first: $('<hr>').insertBefore('p'). Same DOM result, reversed syntax — like .append() vs .appendTo().
.before() inserts siblings outside and above the matched element. .prepend() inserts children inside the matched element as the first child. Use before for labels, headings, or prefixes above a block; use prepend to add content inside a container.
When you insert an existing DOM element before a single target, jQuery moves it (not clones). If you call .before() on multiple matched elements, jQuery clones the inserted element for every target except the last — the original moves to the final target.
Since jQuery 1.4, yes. .before(function(index)) runs once per matched element. Return an HTML string, DOM node, or jQuery object to insert before that element. Inside the function, this refers to the current DOM element. Since jQuery 1.10, a two-argument form also receives the old HTML value.
Did you know?

jQuery’s .before() and .after() have been sibling-insertion pairs since version 1.0, while .insertBefore() and .insertAfter() offer the same behavior with content-first syntax — mirroring the .append() / .appendTo() pattern. Before jQuery 1.9, calling .before() on disconnected nodes could return an unpredictable collection; modern jQuery always returns the original matched set, making method chaining reliable again.

Next: jQuery .clone() Method

Deep-copy matched elements (and optionally events) before inserting duplicates.

.clone() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful