jQuery查找文本和添加类

时间:2014-05-03 06:53:32

标签: jquery css replace

我的HTML结构:

<div id="test-listing">
<article>
<a>Some URL</a><h3>Some Text</h3>
<p>Drink this coffee</p>
</article>
<article><a>Some URL</a><h3>Some Text</h3><p>Drink this Coffee</p></article>
<article><a>Some URL</a><h3>Some Text</h3><p>Drink this Coffeeland</p></article>
<article><a>Some URL</a><h3>Some Text</h3><p>Drink this coffees</p></article>
</div>

我的CSS课程:

.hit-list {
    background: none repeat scroll 0 0 rgba(255, 0, 0, 0.1);
    border-bottom: 1px solid #FF0000;
}

无论区分大小写,我都需要搜索咖啡文本。请注意,咖啡文字可能类似于咖啡咖啡咖啡 Coffeeland ,并将其应用于特定课程。因此产生的代码将是

<div id="test-listing">
      <article><a>Some URL</a><h3>Some Text</h3
       <p>Drink this <span class="hit-list">coffee</span></p>
      </article>
      <article><a>Some URL</a><h3>Some Text</h3
       <p>Drink this <span class="hit-list">Coffee</span></p>
      </article>
      <article><a>Some URL</a><h3>Some Text</h3
       <p>Drink this <span class="hit-list">Coffee</span>land</p>
      </article>
      <article><a>Some URL</a><h3>Some Text</h3
       <p>Drink this <span class="hit-list">coffee</span>s</p>
      </article>  
    </div>

我搜索过相关帖子,但没有找到任何东西,因为我正在处理循环内容。此外,我不需要一个jQuery插件来实现这一目标。

感谢。

2 个答案:

答案 0 :(得分:8)

你可以这样做:

$('div#test-listing article').html(function () {
    return $(this).html().replace(/coffee(?=[^>]*<)/ig, "<span class='hit-list'>$&</span>");
});

如果搜索字词是动态的,您可以执行以下操作:

var term = 'coffee';
$('div#test-listing article').html(function () { 
    return $(this).html().replace(new RegExp(term + "(?=[^>]*<)","ig"), "<span class='hit-list'>$&</span>");
});

Updated Demo

答案 1 :(得分:0)

尝试给文章一个课说class =&#34; article&#34;

<div id="test-listing">
<article class="article">
<a>Some URL</a><h3>Some Text</h3>
<p>Drink this coffee</p>
</article class="article">
<article class="article"><a>Some URL</a><h3>Some Text</h3><p>Drink this Coffee</p></article>
<article class="article"><a>Some URL</a><h3>Some Text</h3><p>Drink this Coffeeland</p></article>
<article class="article"a>Some URL</a><h3>Some Text</h3><p>Drink this coffees</p></article>
</div>

然后使用

$('#test-listing').find('.article').each(function ( i , val) {

// this will replace all coffee or Coffee with html tags you needed
console.log($(this).text().replace(/Coffee|coffee/g, "<span class='hit-list'>Coffee</span>")); 

});