Say I have the following:
<div id="content">content</div>
And I want to insert some stuff before it ** (notice the unclosed div)**:
$("#content").before("<div>pre-pre-content</div><div>pre-content ");
And some then some more after ** (notice I am now closing the div)**:
$("#content").after(" post-content</div><div>post-post-content</div>");
My desired output is:
<div>pre-pre content</div>
<div>
pre-content <div id="content">content</div> post-content
</div>
<div>post-post content</div>
Instead, what I get is:
<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 is automatically "correcting" the unclosed tags.
fiddle
Is there a way to use .wrap() to add different content before and after an element without automatically closing tags?
Note, I cannot do the following because of an unrelated restriction:
$("#content").html("<div>Content before " + $("#content).html() + " Content after</div>")
Say I have the following:
<div id="content">content</div>
And I want to insert some stuff before it ** (notice the unclosed div)**:
$("#content").before("<div>pre-pre-content</div><div>pre-content ");
And some then some more after ** (notice I am now closing the div)**:
$("#content").after(" post-content</div><div>post-post-content</div>");
My desired output is:
<div>pre-pre content</div>
<div>
pre-content <div id="content">content</div> post-content
</div>
<div>post-post content</div>
Instead, what I get is:
<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 is automatically "correcting" the unclosed tags.
fiddle
Is there a way to use .wrap() to add different content before and after an element without automatically closing tags?
Note, I cannot do the following because of an unrelated restriction:
$("#content").html("<div>Content before " + $("#content).html() + " Content after</div>")
Share
Improve this question
edited Apr 19, 2019 at 18:58
double-beep
5,53719 gold badges40 silver badges49 bronze badges
asked Feb 13, 2013 at 0:13
dougmacklindougmacklin
2,62010 gold badges45 silver badges70 bronze badges
1 Answer
Reset to default 5You can't insert partial or unclosed tags. Inserting elements in the DOM must insert only whole elements.
Your choices are:
Extract the element you want to be wrapped in your new element, insert the new container object and then put your original element into the container.
Manipulate the HTML of a parent directly (generally not remended).
Use the jQuery
.wrap()
method which does the option in #1 for you. See here for more info on jQuery's.wrap()
.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744335809a4569109.html
评论列表(0条)