jQuery .before() Method

Beginner
7 min read
Updated: Oct 2026
4 examples
Live preview

What Is .before()?

.before(content) inserts content as the previous sibling of each matched element (since jQuery 1.0). It sits outside the element — use .prepend() to insert inside.

Remember
$("p").before("<b>Hello</b>")     // anchor first
$("<b>Hello</b>").insertBefore("p") // content first (same result)

$("p").before(" Hello ")              // HTML / text
$("p").before(document.createTextNode("Hi"))
$(".box").before($("h2"))             // move existing node
NeedUse
Sibling above (anchor first)$(el).before(content)
Sibling above (content first)$(content).insertBefore(el)
Sibling below$(el).after(content)
First child inside$(el).prepend(content)

How to Use .before()

Select the anchor element, then pass what should appear just above it.

  1. Select the element(s) that should stay in place (the anchors).
  2. Call .before(content) with HTML, a node, a jQuery object, or a callback.
  3. Content becomes the previous sibling of each match — outside the element.
  4. Chain further methods on the same original collection if needed.
PieceRequired?Role
Matched setYesAnchor element(s) — content goes before them
contentYes*HTML, Element, Text, Array, or jQuery (*or callback)
Callback (1.4+)Optionalfunction(index); since 1.10 also (index, html)
Return (1.9+)—Original matched set (unchanged)

Pseudocode

Pseudocode
for each matched element el:
    if el has no parent:
        do nothing          // jQuery 1.9+
        continue

    if content is a function:
        piece = content(index [, el.innerHTML])
    else:
        piece = content

    insert piece as previous sibling of el

    // existing DOM node + one target  → move
    // existing DOM node + many targets → clone for all but last

return original matched set

Cheat Sheet

Keep these facts handy while inserting siblings.

TopicDetail
Syntax.before(content [, content…])
Callback.before(function(index) { … }) since 1.4
PositionPrevious sibling (outside the element)
SincejQuery 1.0 (callback 1.4; html arg 1.10)
vs insertBeforeSame task; anchor-first vs content-first
vs afterAbove vs below as siblings
vs prependOutside sibling vs inside first child
No parent (1.9+)No effect; returns original set

Live Preview

Insert content before <p id="line">is what I said...</p> and watch the previous sibling appear.

Browser demo of .before() — same idea as the examples below.

is what I said...

Result
$("p").before(" Hello ")
→ Hello is what I said...

jQuery Examples

Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.

Example 1 — Insert HTML Before Paragraphs

Add content as the previous sibling of every <p>.

jQuery
$("p").before("<b>Hello</b> ");
Try It Yourself

How It Works

  1. Select. $("p") matches every paragraph.
  2. Parse. jQuery turns the HTML string into a <b> node.
  3. Insert. That node becomes the previous sibling of each <p>.
  4. Outside. The bold text is not inside the paragraph — it sits before it.

Example 2 — Insert a Text Node

Insert plain text without HTML parsing.

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

How It Works

  1. Create. createTextNode("Hello ") builds a real text node.
  2. Insert. jQuery places it as the previous sibling of each <p>.
  3. No parse. Angle brackets stay literal text.
  4. When to use. Safer path for plain user text (still validate input).

Example 3 — Move an Existing Element

Insert a jQuery object before the paragraph — with one target, it moves.

jQuery
$("p").before($("b"));
// <b> leaves its old parent and lands before <p>
Try It Yourself

How It Works

  1. Select content. $("b") points at an existing bold element.
  2. One target. jQuery detaches it and inserts it before the paragraph.
  3. Many targets. Clones fill every match except the last.
  4. Takeaway. Existing nodes move when there is only one anchor.

Example 4 — Insert With a Callback

Return different content per element (since jQuery 1.4).

jQuery
$(".item").before(function (index) {
  return "<span>#" + (index + 1) + "</span> ";
});
Try It Yourself

How It Works

  1. Per element. The callback runs once for each .item.
  2. Index. Zero-based position in the matched set.
  3. Return. Returned markup becomes the previous sibling.
  4. this. Inside the function, this is the current DOM element.

Edge Cases & Pitfalls

Check these before using .before() in production.

outside

Sibling, not child

.before() inserts outside the element. To add inside at the top, use .prepend().

xss

Untrusted HTML can execute code

Script tags and event attributes in inserted strings are dangerous. Prefer text nodes or escaped content.

move

Existing nodes move, not copy

One target removes the node from its old parent. Many targets clone for all but the last.

orphan

No parent → no effect (1.9+)

Calling .before() on a disconnected node does nothing and still returns the original set.

Browser Support

.before() has been part of jQuery since 1.0. The callback form arrived in 1.4 (with an optional HTML argument since 1.10). Return-value behavior for disconnected nodes was clarified in jQuery 1.9.

✓ Stable · jQuery 1.0+

jQuery .before()

Supported in all browsers that run jQuery 1.0+. Prefer a current jQuery 3.x build for modern projects.

100% jQuery core method
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: Safe for any project that already loads jQuery. Use .before() for siblings above; use .prepend() when you need content inside.

Performance Notes

ApproachCostBest for
One .before() with a fragmentFewer reflowsMany nodes at once
Loop of tiny .before() callsMore DOM workOccasional single inserts
Multiple arguments in one callSingle passInserting several siblings together

Batch sibling inserts when possible. Avoid calling .before() inside a tight loop when hundreds of nodes are involved.

Key Takeaways

  • Role: insert content as the previous sibling of matched elements.
  • Twin: .insertBefore() does the same job with reversed syntax.
  • Outside: use .prepend() if you need the first child inside.
  • Safety: never insert untrusted HTML strings.

One line: .before() adds a sibling above an element — perfect for headings, labels, and prefixes.

Frequently Asked Questions

.before() inserts content immediately before each matched element as a previous sibling — outside the element, not inside it. It accepts HTML strings, DOM elements, text nodes, arrays, jQuery objects, or a callback (since 1.4). Returns the original matched set for chaining. Available since jQuery 1.0.
.before() inserts as the previous sibling. .after() inserts as the next sibling. Both operate outside the matched element.
Same job, reversed syntax. With .before(), the anchor comes first: $('p').before('<b>Hi</b>'). With .insertBefore(), the content comes first: $('<b>Hi</b>').insertBefore('p').
.before() adds a sibling above the element. .prepend() adds a child inside the element as the first child.
With one matched target, jQuery moves the inserted element. With multiple targets, it clones for every match except the last — the original moves to the final target.
Since jQuery 1.4, yes. .before(function(index)) runs once per match. Since 1.10, the callback can also receive the old HTML: function(index, html). Return content to insert; this is the current element.
As of jQuery 1.9, .before() on a node without a parent has no effect and still returns the original set.

Next: .clone()

Copy elements (and optionally events/data) before inserting them elsewhere.

.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.

8 people found this page helpful