After and Before

Insert content outside elements, as siblings.

Syntax$(el).before(content); $(el).after(content);

Where append/prepend work inside an element, these place content outside it, as siblings:

  • .before() — insert just before the element.
  • .after() — insert just after the element.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A form validator inserts an error message sibling after each invalid input using .after('<span class="err">Required</span>').
  • A section divider uses .before() to inject a <hr> separator before a dynamically added content block.
  • A breadcrumb builder uses .after() to insert arrow separators between each generated breadcrumb item.

More examples

Insert error message after input

.after() inserts content as a sibling immediately after the input, which keeps the error inline with the field.

Example · html
<input id="email" type="email" placeholder="Email" />
<button id="validate">Validate</button>
<script>
$(function () {
  $("#validate").click(function () {
    $(".err-msg").remove();
    var val = $("#email").val();
    if (!val.includes("@")) {
      $("#email").after("<span class='err-msg' style='color:red'> Invalid email</span>");
    }
  });
});
</script>

Insert a divider before a section

.before("<hr />") inserts the separator just before the section element, keeping the divider paired with its section.

Example · html
<div id="main">Main content</div>
<button id="addSection">Add section</button>
<script>
$(function () {
  var n = 0;
  $("#addSection").click(function () {
    n++;
    var $sec = $("<div>").text("New section " + n);
    $sec.before("<hr />");
    $("#main").after($sec);
  });
});
</script>

Wrap selected text with a span

Replaces the plain word in the HTML string with a <mark> element, effectively inserting a sibling inline element.

Example · html
<p id="quote">jQuery simplifies DOM manipulation.</p>
<button id="mark">Highlight "DOM"</button>
<script>
$(function () {
  $("#mark").click(function () {
    var html = $("#quote").html();
    $("#quote").html(
      html.replace("DOM", "<mark>DOM</mark>")
    );
  });
});
</script>

Discussion

  • Be the first to comment on this lesson.