比如我有如下html代码<div id="target">
<p>微软Windows 10操作系统</p></div>我希望js执行后把他变成这样<div id="target">
<p>微软<span class="myclass">Windows 10</span>操作系统</p></div>该如何实现呢?
1 回答
![?](http://img1.sycdn.imooc.com/5333a0490001f9ff02200220-100-100.jpg)
智慧大石
TA贡献1946条经验 获得超3个赞
function replaceTextWithSpanWrap(id, tagName, className) {
Array.prototype
.slice
.call(document.getElementById(id).getElementsByTagName(tagName))
.map(function(node) {
node.innerHTML = node.innerHTML.replace(/[A-Za-z0-9\s]+/g, function(text) {
return '<span class="' + className + '">' + text + '</span>';
});
});
}
replaceTextWithSpanWrap('target', 'p', 'myclass');
添加回答
举报
0/150
提交
取消