Insert content before and after element without autoplay tags
Let's say I have the following:
<div id="content">content</div>
And I want to insert some things before this ** (note the unclosed div) **:
$("#content").before("<div>pre-pre-content</div><div>pre-content ");
And a little more, after ** (note, I'm closing the div now) **:
$("#content").after(" post-content</div><div>post-post-content</div>");
My desired output:
<div>pre-pre content</div>
<div>
pre-content <div id="content">content</div> post-content
</div>
<div>post-post content</div>
Instead, I get:
<div>pre-pre content</div>
<div>pre-content</div>
<div id="content">content</div>
<div>post-content</div>
<div>post-post content</div>
Because jQuery automatically "fixes" unclosed tags.
Is there a way to use .wrap () to add different content before and after an element without automatically closing the tags?
Please note, I can not do the following due to an unrelated constraint:
$("#content").html("<div>Content before " + $("#content).html() + " Content after</div>")
source to share
You cannot insert partial or unclosed tags. Inserting elements into the DOM should only insert whole elements.
Your options:
-
Extract the element you want to wrap in a new element, insert a new container object, and then insert it into the container.
-
Manipulate the parent's HTML directly (usually not recommended).
-
Use the jQuery method
.wrap()
that does option # 1 for you. See here for more information on jQuery.wrap()
.
source to share