Well, here is one way to do this (although I suspect there are more concise, efficient and, frankly, better ways to do this):
var needle = 'ipsum'; var wrappingText = ' wrapper '; $('p').each( function(){ var haystack = $(this).text(); $(this).text(haystack.replace(needle, wrappingText + needle + wrappingText)); });
This obviously depends on the text contained in the p element, but with easy modification to any other specific element or element class.
JS Fiddle demo
And here is the way to wrap the needle with html (although, again, this is probably not the most beautiful way):
HTML:
<form action="" method="post"> <fieldset> <label for="needle">Search for this text: </label> <input type="text" name="needle" id="needle" placeholder="Example: 'sit'" /> </fieldset> <fieldset> <label for="wrapper">Wrap with this:</label> <input id="wrapper" name="wrapper" type="text" placeholder="Example: <em>" /> </fieldset> <fieldset id="choose"> <input type="radio" name="wrapWith" id="text" value="0" checked /><label for="html">Text</label> <input type="radio" name="wrapWith" id="html" value="1" /><label for="html">HTML</label> </fieldset> <fieldset> <input type="submit" value="search" /> </fieldset> </form> <p>Lorem ipsum dolor sit amet.</p> <p>Lorem ipsum dolor sit amet.</p>
JQuery
$('form').submit( function(){ var needle, wrapper, haystack; if ($('#needle').val().length >= 1) { needle = $('#needle').val(); } else { needle = 'ipsum'; } if ($('#wrapper').val().length >= 1) { wrapper = $('#wrapper').val(); } else { wrapper = 'wrap'; } var wrappingText = 'wrapper'; $('p').each( function(){ if ($('#text').is(':checked')) { haystack = $(this).text(); $(this).text(haystack.replace(needle, wrapper + needle + wrapper)); } else if ($('#html').is(':checked')) { haystack = $(this).text(); $(this).html(haystack.replace(needle, wrapper + needle + wrapper.replace('<', '</'))); } }); return false; });
JS Fiddle demo .
source share