我的HTML代码:
<body>Firebrand will tend to burn any bricks out there. so the best idea is to ignore any active firebrand if you are a bricks. Otherwise, you can challenge a firebrand if you have the proper quality to keep up with their latest technology. And don't mess up with firebrand if you are a robber.</body>
我想在体内找到任何“ firebrand”,并用jQuery替换为
<span class="firebrand">firebrand</span>
最佳答案
只需通过DOM递归,同时使用:.replace(/(firebrand)/gi, '<span class="firebrand">$1</span>')
在每个文本内容上。
function firebrand($el) {
$el.contents().each(function () {
if (this.nodeType == 3) { // Text only
$(this).replaceWith($(this).text()
.replace(/(firebrand)/gi, '<span class="firebrand">$1</span>'));
} else { // Child element
firebrand($(this));
}
});
}
firebrand($("body"));
关于jquery - jQuery:使用某些元素查找并包装textnode,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1788939/