Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 533
Dev1997 Avatar asked Mar 18 '16 10:03

Dev1997


People also ask

How do you append before an element?

The insertBefore() method inserts HTML elements before the selected elements. Tip: To insert HTML elements after the selected elements, use the insertAfter() method.

What is prepend jQuery?

prepend() method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the last child, use . append() ).

Which jQuery DOM method is used to insert content before the selected elements?

insertBefore( target ) A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter.

What is append and prepend in jQuery?

append() & . prepend() .append() puts data inside an element at the last index; while. . prepend() puts the prepending element at the first index.


Video Answer


1 Answers

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>");
like image 197
Rajshekar Reddy Avatar answered Sep 24 '22 23:09

Rajshekar Reddy