javascript - 用字符串替换标签名称
问题描述
假设我有一些 HTML 代码,例如:
"Hello, my <strong>name</strong> is Nanoo."
如何<strong>
用字符串替换标签?
例如:
"Hello, my **name** is Nanoo."
(用 替换<strong>
标签**
)
我可能可以使用该replace()
功能,但是我想有效地做到这一点。
谢谢你的帮助。
解决方案
使用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>
推荐阅读
- node.js - 哪种方法可以立即将经过数学处理的数据从服务器分区传输到任何前端?
- android - 如何以编程方式打开我的应用程序的免打扰权限屏幕?
- c# - C# 不可为空的字段:Lateinit?
- javascript - 启用/禁用按钮问题
- python - Python代码问题。我用python做了一个简单的彩票系统。如何在每次重置为 1000 时停止变量 b?
- php - 如何使用 PHP 更改 CSS 中的颜色?
- javascript - React.js 将元素附加到现有的 svg
- django - 尽管设置良好,但 Django ModelChoiceField 初始值不起作用
- linux - 如何在shell中创建一个切换功能,在一个呼叫上打开,在另一个呼叫上关闭?
- vue.js - npm 错误!纤维@4.0.2 安装:`node build.js || 在 Nuxt 中安装 Vuetify 时的 nodejs build.js`