Highlight parent using jQuery?

Say, for example, that I have a web page.

<ul> <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li> <li>Aliquam tincidunt mauris eu risus.</li> <li>Vestibulum auctor dapibus neque.</li> </ul> 

I want to find all instances of the word "Lorem" and manipulate them in two ways:

  • Wrap it with <mark> HTML5
  • Run .addClass('look-at-me'); in its parent element.

So the resulting HTML will be

 <ul> <li class="look-at-me"><mark>Lorem</mark> ipsum dolor sit amet, consectetuer adipiscing elit.</li> <li>Aliquam tincidunt mauris eu risus.</li> <li>Vestibulum auctor dapibus neque.</li> </ul> 

I read all the comments, highlighted the word with jQuery , and I played with the JS code from highlight: JavaScript text fitting the jQuery plugin , but both deal with ONLY highlighting the word in context. I manipulated the code to wrap the word using <mark> , but I am not good enough at JS to achieve goal # 2 of allocating the parent container. I really want to see your useful suggestions. Thanks!

EDIT: DECIDE! http://jsfiddle.net/GB8zP/1/

+4
source share
3 answers
 $('li').each(function () { $(this).html($(this).html().replace(/Lorem/ig, "<mark>$&</mark>")); if ($(this).text().toLowerCase().indexOf('lorem') >= 0) $(this).addClass('look-at-me'); }); 

JsFiddle example

+4
source

try it

  $("ul li:contains('Lorem')").each(function() { $(this).html($(this).html().replace("Lorem","<mark>Lorem</mark>")); $(this).parent().addClass("look-at-me"); }) 
+2
source

Here is what I came up with: http://jsfiddle.net/c24w/cZegf/

HTML

 <ul id="test"> <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li> <li>Aliquam lorem tincidunt mauris eu Lorem risus.</li> <li>Vestibulum auctor dapibus neque.</li> </ul> 

Js

 $('li', '#test').each(function highlightElement(i, e) { e = $(e); e.html(e.html().replace(/lorem/gi, function handleMatch(match) { if (!e.hasClass('look-at-me')) e.addClass('look-at-me'); return '<match>' + match + '</match>'; })); }); 

CSS

 .look-at-me { background: #f00; } match { background: #ff0; } 

Info

Regular expression:

 /lorem/gi ↑↑ ||_ case-insensitive |_ matches multiple (global) 

Match Function:

handleMatch(match) - every successful regular expression handleMatch(match) is passed to this function, where the matched text is surrounded by <match></match> . This implementation makes it easy to change the exact pattern you want to highlight, since only the regular expression needs to be updated. In addition, if necessary, the parent match element is highlighted.

+1
source

All Articles