Search code examples
javascriptjquerycssstylesheetmarkup

Change style of all occurrences of a string


I want my site title to display in a unique font from the rest of the content every time it appears in a heading, for branding reasons. For simplicity, let's pretend my special font is Courier and my company is called SparklePony. So, a line like,

<h1 class="title">SparklePony Board of Directors</h1>

would show a headline with the word SparklePony in Courier and Board of Directors in my site default font, Arial. (Yes, I know this would be hideous.)

I've tried using a jQuery string replacement, but I don't want to replace the string, I just want to see it in Courier (adding a class to just that word, or something of the like.) Replacing SparklePony with <span class="sparkle-pony">SparklePony</span> caused the whole ugly string with tags and everything to show on my site, rather than adding the class.

Am I doing something wrong with my string replace, or is there a better way to style all occurrences of a string?


Solution

  • You can do it like this - specifying the selector you want - #('h1') or by class.

    $('.title').html(function(i,v){    
       return v.replace(/SparklePony/g,'<span class="sparkle">SparklePony</span>');
    });
    ​
    

    http://jsfiddle.net/cQjsu/