Insert Content Before and After an Element Without

2019-07-03 15:07发布

问题:

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>")

回答1:

You can't insert partial or unclosed tags. Inserting elements in the DOM must insert only whole elements.

Your choices are:

  1. 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.

  2. Manipulate the HTML of a parent directly (generally not recommended).

  3. Use the jQuery .wrap() method which does the option in #1 for you. See here for more info on jQuery's .wrap().