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?
The insertBefore() method inserts HTML elements before the selected elements. Tip: To insert HTML elements after the selected elements, use the insertAfter() method.
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() ).
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.
append() & . prepend() .append() puts data inside an element at the last index; while. . prepend() puts the prepending element at the first index.
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>");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With