jQuery在没有自动关闭标签的元素之前和之后插入内容

说我有以下内容:

content

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

 $("#content").before("
pre-pre-content
pre-content ");

然后再说一些(注意我现在正在关闭div)

 $("#content").after(" post-content
post-post-content
");

我想要的输出是:

 
pre-pre content
pre-content
content
post-content
post-post content

相反,我得到的是:

 
pre-pre content
pre-content
content
post-content
post-post content

因为jQuery会自动“纠正”未关闭的标签。

小提琴

有没有办法使用.wrap()在元素之前和之后添加不同的内容而不自动关闭标签?

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

 $("#content").html("
Content before " + $("#content).html() + " Content after
")

您无法插入部分或未封闭的标签。 在DOM中插入元素必须只插入整个元素。

你的选择是:

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

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

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