I would like to highlight search terms on a page, but not mess with any HTML tags. I was thinking of something like:
$('.searchResult *').each(function() {
$(this.html($(this).html().replace(new RegExp('(term)', 'gi'), '<span class="highlight">$1</span>'));
)};
However, $('.searchResult *').each
matches all elements, not just leaf nodes. In other words, some of the elements matched have HTML inside them. So I have a few questions:
- How can I match only leaf nodes?
- Is there some built-in jQuery RegEx function to simplify things? Something like:
$(this).wrap('term', $('<span />', { 'class': 'highlight' }))
- Is there a way to do a simple string replace and not a RegEx?
- Any other better/faster way of doing this?
Thanks so much!