jQuery:查找并包装带有某些元素的textnode [英] jQuery : find and wrap textnode with some element
本文介绍了jQuery:查找并包装带有某些元素的textnode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的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>
我想在体内找到任何火力烙印",并用jQuery替换为<span class="firebrand">firebrand</span>
I want to find any "firebrand" inside the body and replace it with <span class="firebrand">firebrand</span>
with jQuery
推荐答案
只需使用以下内容即可遍历DOM:
Just recurse through the DOM, while using:
.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:查找并包装带有某些元素的textnode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文