JQuery: Append before an element

Viewed 41266

Using JQuery I have appended a div into a container called .mobile-sub. I call the append by doing:

$('.s2_error').addClass("revive");
$('.revive').parent(".mobile-sub").append('<div>mydiv</div>');

It works fine but the problem is that it is placing the div after the .s2_error tag whereas I need it to be placed before so the end result HTML will look like this:

<div>mydiv</div>
<p class="s2_error">Error</p>

Any ideas?

5 Answers

You can do it two ways:

  1. Before

    $(".s2_error").before("<div>mydiv</div>");
    
  2. InsertBefore

    $("<div>mydiv</div>").insertBefore(".s2_error");
    

Both do the same but they are syntactically different.

Related