jQuery找到最内在的内容

时间:2013-09-28 06:00:34

标签: jquery regex dom jquery-selectors selector

我想找到位于DOM末尾的每个元素的内部内容或文本,并将其替换为<span class="red">content</span>

这就是我正在使用的

regex = new RegExp("\\b"+word+"\\b", "gi");

$(this).find("*:not(:has(*))").each(function(){
    this.innerHTML = this.innerHTML.replace(
        regex, function(matched) {
            return "<span class=\"" + className + "\">" + matched + "</span>";});
});

但问题是,如果结构为<div>one two</div>,则在将one替换为<div><span class="red">one</span> two<div>后,我的选择器无法找到第二个two

请查看jsFiddle此处two未突出显示

2 个答案:

答案 0 :(得分:1)

你需要的是

var words = ['one', 'two'];
var regex = new RegExp("\\b(" + words.join('|') + ")\\b", "gi");
$('#outer').find(":not(:has(*))").html(function (idx, html) {
    return html.replace(regex, '<span class="red">$1</span>');
});

演示:Fiddle

问题是,一旦循环执行,myId元素将具有span元素作为子元素,因为one被替换为<span class="red">one</span>,导致您的选择器*:not(:has(*))失败

答案 1 :(得分:1)

试试这个:

var words = ['one','two'];
regex = new RegExp("\\b("+words.join('|')+")\\b", "gi");
$('#outer').find("*:not(:has(*))").each(function(){
     this.innerHTML = this.innerHTML.replace(regex, function(matched) {
          return "<span class=\"red\">" + matched + "</span>";
     });
});

演示:http://jsfiddle.net/jpWaw/1/