0

A page contains a search input field and a table.

How to highlight, in the table, all substrings that match the text in the input field?

I have tried this, but it changes the background of the td element.

$(".projects-list > tbody > tr > td:contains('"+$(this).val()+"')").css("background", "#6a5acd");

How to highlight only the part of text that match?

Nanego
  • 1,890
  • 16
  • 30

3 Answers3

3

You can use split(matchingText).join(wrappedMatchingText) on each of the target cells.

$('.projects-list td').each(function (i, e) {
    var $e = $(e);
    $e.html($e.html().split(text).join('<span class="matching">' + text + '</span>'));
});

This would wrap all instances of the target string(stored in the variable text) inside individual span.matching tags

DEMO DEMO

tewathia
  • 6,890
  • 3
  • 22
  • 27
  • Just investigate the DOM to see the sea of nested `.matching` elements. – Ram Jan 28 '14 at 09:14
  • @BlackSheep On clicking the 'highlight' button multiple times, you mean? Fixed, I think. See the updated fiddle in my answer. – tewathia Jan 28 '14 at 09:27
  • 1
    Yes, the updated fiddle doesn't create nested elements, just a note, Firefox doesn't support the non-standard `innerText` property. It supports `textContent`. – Ram Jan 28 '14 at 09:41
0

Here is html,

<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>cell 1</td>
<td>cell 2</td>
</tr>
<tr>
<td>row 2</td>
<td>row 2</td>
</tr>
</table>

Here is Jquery,

$(document).ready(function(){

$("td:contains('cell 1')").css("color","#6a5acd");//color highlighting 

})

And reference link,

http://jsfiddle.net/dhana36/fe485/

dhana
  • 6,487
  • 4
  • 40
  • 63
0

Try

if (!RegExp.escape) {
    RegExp.escape = function (s) {
        return s.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
    };
}

then

$(".projects-list > tbody > tr > td .highlighted").contents().unwrap();
var search = RegExp.escape(this.value);
$(".projects-list > tbody > tr > td").html(function (i, text) {
    return text.replace(new RegExp('(' + search + ')', 'gi'), '<span class="highlighted">$1</span>')
})

Demo: Fiddle

Note: If the cells has html contents that is not handled here

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • 1
    Why does this break down if I press backspace, when there is just one character in the `input` tag, and try to type something? – tewathia Jan 28 '14 at 09:33