在没有自动丢失标记的图元之前和之后插入内容

Insert Content Before and After an Element Without Autoclosing tags

本文关键字:图元 之后 插入      更新时间:2023-09-26

假设我有以下内容:

<div id="content">content</div>

我想在它之前插入一些东西**(注意未关闭的div)**:

$("#content").before("<div>pre-pre-content</div><div>pre-content ");

**之后还有一些(注意,我现在正在关闭div)**:

$("#content").after(" post-content</div><div>post-post-content</div>");

我想要的输出是:

<div>pre-pre content</div>
<div>
    pre-content <div id="content">content</div> post-content
</div>
<div>post-post content</div>

相反,我得到的是:

<div>pre-pre content</div>
<div>pre-content</div>
<div id="content">content</div>
<div>post-content</div>
<div>post-post content</div>

因为jQuery正在自动"更正"未关闭的标记。

小提琴

有没有一种方法可以使用.wrap()在元素前后添加不同的内容而不自动关闭标记?

注意,由于不相关的限制,我不能执行以下操作:

$("#content").html("<div>Content before " + $("#content).html() + " Content after</div>")

不能插入部分或未闭合的标记。在DOM中插入元素必须只插入整个元素。

您的选择是:

  1. 提取要包装在新元素中的元素,插入新的容器对象,然后将原始元素放入容器中。

  2. 直接操作父级的HTML(通常不推荐)。

  3. 使用jQuery .wrap()方法为您执行#1中的选项。有关jQuery的.wrap()的更多信息,请参阅此处。