views:

63

answers:

3

I'm applying a style to a certain phrase on our website over and over again. Is there a way to search the page for instances of that phrase and apply that style automatically?

Example:

<div>
     This is what you get from <span class="comp">Company Name</span>. 
     We do all kinds of things here at <span class="comp">Company Name</span>.
</div>
A: 

sure... http://docs.jquery.com/Selectors/contains#text

$("div:contains('Conpany Name')").css("text-decoration", "underline");
David
That will style the entire div
CMS
As CMS said, that will style the entire div, and it would most likely be better to use .addClass("comp") rather than manually setting a new CSS style in this case.
Jay
oops... It was off the cuff to find the text, but I'm sure it wouldn't take much more to just style the text in question.
David
A: 
var body = document.getElementByTagName("body")[0].innerHTML;

body.replace(/Company Name/g, '<span class="comp">Company Name</span>');
document.getElementByTagName("body")[0].innerHTML = body;

The above should get everything in the body and replace it with your span and that doesnt need jQuery.

AutomatedTester
I think you mean ('<span class="comp">Company Name</span>'); or escape the middle "s, as the current code would throw an error.
Jay
i did mean it that way. Thanks for point it out
AutomatedTester
`<div title="Company Name are good!!">blah blah</div>` -> whoops. Don't process HTML with regex.Bonus: the innerHTML writeback also destroys any form data, event handlers and JS/jQuery references you have. Don't process HTML with regex.
bobince
+2  A: 

You could take a look at these questions:

Both of the top answers point to the highlight plugin for jQuery.

nickf
I used the highlight plugin. Thanks a bunch!
nlinus