Question

I have a HTML page in which I have some content that user can search. Here is the example HTML

 <span class="name">Red Apple</span>
 <span class="location">Texas</span>
 <span class="date">Mon, Apr 07, 11:15 AM</span>

 <span class="name">California Orange</span>
 <span class="location">California</span>
 <span class="date">Mon, Apr 07, 11:15 AM</span>

If the user enters "Apr" and hits search I want to add a div to the two matching span content like this

<span class="date">Mon, <div class="red">Apr<div> 07, 11:15 AM</span>

Later when the user hits clear search I want to remove these as well.

What is the best way to do this using JQuery?

Was it helpful?

Solution

Since you don't want to use a plugin, you could do this using replace():

$('span').html(function() {
    return $(this).text().replace(searchString, '<div class="red">' + searchString + '</div>');
});

Just to note, nesting a div within a span is not valid. Also, the above example is case sensitive (ie. red will not match the word Red).

In order to remove the highlighting, you can use unwrap(), targeting the div.red that has been added:

$('div.red').contents().unwrap();

Here's a fiddle

OTHER TIPS

Try higlighting jQuery plugin

Plugin

js

var hightlight = $('#highlight'),
    txt = $('#txt');
$('#search').click(function () {
    hightlight.highlight(txt.val());
});
$('#clear').click(function () {
    hightlight.removeHighlight();
});

HTML

<div id="highlight"> <!--  Wrap your searching area in div-->
 <span class="name">Red Apple</span>
 <span class="location">Texas</span>
 <span class="date">Mon, Apr 07, 11:15 AM</span>
 <span class="name">California Orange</span>
 <span class="location">California</span>
 <span class="date">Mon, Apr 07, 11:15 AM</span>

</div>
<input type="text" id="txt" /> <!-- Searching textbox -->
<input type="button" id="search" value="serach" /> <!-- Search on button click-->
<input type="button" id="clear" value="clear" /> <!-- clear highlight on button click-->

CSS

.highlight {
    background-color: red
}

Fiddle Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top