简体   繁体   中英

JQuery: Append before an element

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?

Using various options like below

insertBefore

$("<div>mydiv</div>").insertBefore('.mobile-sub .s2_error');

OR by writing another selector inside your insertBefore

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

Meaning

$('thisElementShouldBe').insertBefore('thisElement');


prepend

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

So <div>mydiv</div> will always be added as the first child of mobile-sub


before

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

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.

You want to add element as first child. You need to use .prepend() instead of .append() :

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

You can also use .insertBefore () :

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

or .before() :

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

You can use .insertBefore()

Insert every element in the set of matched elements before the target.

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

OR, .before()

Insert content, specified by the parameter, before each element in the set of matched elements.

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

Note: The .before() and .insertBefore() methods perform the same task. The major difference is in the syntax—specifically, in the placement of the content and target.

.insertBefore( target )

Description: Insert every element in the set of matched elements before the target.

or

.before( content [, content ] )

Description: Insert content, specified by the parameter, before each element in the set of matched elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM