Highlight search terms (select only leaf nodes)
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':