Slimshadddyyy
Slimshadddyyy

Reputation: 4073

jQuery Find Text and Add class

My HTML Structure:

<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>

My CSS class:

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

I need to search the text coffee regardless of case sensitivity. Note the coffee text could be like coffee, coffees, Coffee, Coffeeland and apply it specific class. So the resulting code would be

<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>

I have searched related posts but did not find any thing as I am dealing with content inside loop. Also I do not need a jQuery plugin to achieve this.

Thanks.

Upvotes: 0

Views: 3007

Answers (2)

Amit Joki
Amit Joki

Reputation: 59232

You can do this:

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

If the search term is dynamic, you can do this:

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

Updated Demo

Upvotes: 8

sshet
sshet

Reputation: 1160

Try to give article a class say class="article"

<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>

Then using

$('#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>")); 

});

Upvotes: 0

Related Questions