首页 > 解决方案 > 用字符串替换标签名称

问题描述

假设我有一些 HTML 代码,例如:

"Hello, my <strong>name</strong> is Nanoo."

如何<strong>用字符串替换标签?

例如:

"Hello, my **name** is Nanoo."

(用 替换<strong>标签**

我可能可以使用该replace()功能,但是我想有效地做到这一点。
谢谢你的帮助。

标签: javascripthtmldom

解决方案


使用parentNode.replaceChild(newChild, oldChild); .

// on DOMContentLoaded 
document.querySelectorAll('strong').forEach(function(ele) { // for each strong tag
    var newTag = document.createTextNode('**' + ele.textContent + '**');
    ele.parentNode.replaceChild(newTag, ele);
})
<p>Hello, my <strong>name</strong> is Nanoo.</p>


推荐阅读