如何用 DIV 替换 HTML 标签并稍后关闭它
How to replace an HTML tag with only an opening DIV and close it later on
我试图找到答案,但只是偶然发现了 replaceWith Automatically Closes the Tag and Replace HR Element with Open Div - 既找到了第一个元素又找到了最后一个元素,并用 div
包裹起来。
在我的例子中,我们有一个 HTML 在 p
元素中包含多个文本,例如:
<p>
[spoiler]
</p>
<p>
Text to hide.
</p>
<p>
[/spoiler]<br />
</p>
<p>
Text in-between.
</p>
<p>
[spoiler]
</p>
<p>
Second Text to hide.
</p>
<p>
[/spoiler]
</p>
<p>
More Text …
</p>
现在我需要找到开始的 [spoiler]
标签并将它们的包装 p
标签替换为开始的 <div class="spoiler">
标签。接下来我需要找到结束的 [/spoiler]
标签并将它们替换为结束的 </div>
.
Jquery 的 replaceWith()
总是关闭插入的元素。
所以我的简单方法不起作用:
$(this).find('p:contains([spoiler])').replaceWith('<div class="qa-spoiler">');
$(this).find('p:contains([/spoiler])').replaceWith('</div>');
我无法控制 HTML 标记。
怎么做?
PS:将标题从 "replaceWith without closing Tag and wrapping a Div around multiple p tags" 更改为 "How to replace an HTML tag with only an opening DIV and close it later on"。
此逻辑找到包含开始和结束剧透标记的 p 标签之间的所有元素,并将它们包装在您想要的 div 中。然后它返回并删除剧透标签,有效地 "replacing" 它们。
$('p:contains([spoiler])').each(function(){
$(this).nextUntil('p:contains([/spoiler])').wrapAll('<div class="qa-spoiler">');
}).remove();
$('p:contains([/spoiler])').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
[spoiler]
</p>
<p>
Text to hide.
</p>
<p>
Text to hide.
</p>
<p>
[/spoiler]<br />
</p>
<p>
Text in-between.
</p>
<p>
[spoiler]
</p>
<p>
Second Text to hide.
</p>
<p>
[/spoiler]
</p>
<p>
More Text …
</p>
我试图找到答案,但只是偶然发现了 replaceWith Automatically Closes the Tag and Replace HR Element with Open Div - 既找到了第一个元素又找到了最后一个元素,并用 div
包裹起来。
在我的例子中,我们有一个 HTML 在 p
元素中包含多个文本,例如:
<p>
[spoiler]
</p>
<p>
Text to hide.
</p>
<p>
[/spoiler]<br />
</p>
<p>
Text in-between.
</p>
<p>
[spoiler]
</p>
<p>
Second Text to hide.
</p>
<p>
[/spoiler]
</p>
<p>
More Text …
</p>
现在我需要找到开始的 [spoiler]
标签并将它们的包装 p
标签替换为开始的 <div class="spoiler">
标签。接下来我需要找到结束的 [/spoiler]
标签并将它们替换为结束的 </div>
.
Jquery 的 replaceWith()
总是关闭插入的元素。
所以我的简单方法不起作用:
$(this).find('p:contains([spoiler])').replaceWith('<div class="qa-spoiler">');
$(this).find('p:contains([/spoiler])').replaceWith('</div>');
我无法控制 HTML 标记。
怎么做?
PS:将标题从 "replaceWith without closing Tag and wrapping a Div around multiple p tags" 更改为 "How to replace an HTML tag with only an opening DIV and close it later on"。
此逻辑找到包含开始和结束剧透标记的 p 标签之间的所有元素,并将它们包装在您想要的 div 中。然后它返回并删除剧透标签,有效地 "replacing" 它们。
$('p:contains([spoiler])').each(function(){
$(this).nextUntil('p:contains([/spoiler])').wrapAll('<div class="qa-spoiler">');
}).remove();
$('p:contains([/spoiler])').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
[spoiler]
</p>
<p>
Text to hide.
</p>
<p>
Text to hide.
</p>
<p>
[/spoiler]<br />
</p>
<p>
Text in-between.
</p>
<p>
[spoiler]
</p>
<p>
Second Text to hide.
</p>
<p>
[/spoiler]
</p>
<p>
More Text …
</p>