0

I am building a site for a friend, the site has launched, now he tells me he wants his site name to appear green everywhere it appears on the website.

Immediately, I thought of the plugin SEO Smart Links, which automatically links a string of text. Is there anything like this for applying styles or classes to a string of text?

OR a suggestion for another method to complete this task?

0

2 Answers 2

2

If it's purely for setting the style of the text you may want to use JavaScript/jQuery instead. Here's a quick sample that would replace all instances of "ipsum" with

<span class="red">ipsum</span>

And the full code:

// Find text in descendents of an element, in reverse document order
// pattern must be a regexp with global flag
//
function findText(element, pattern, callback) {
    for (var childi= element.childNodes.length; childi-->0;) {
        var child= element.childNodes[childi];
        if (child.nodeType==1) {
            findText(child, pattern, callback);
        } else if (child.nodeType==3) {
            var matches= [];
            var match;
            while (match= pattern.exec(child.data))
                matches.push(match);
            for (var i= matches.length; i-->0;)
                callback.call(window, child, matches[i]);
        }
    }
}

findText(document.body, /ipsum/g, function(node, match) {
    var span= document.createElement('span');
    span.className= 'red';
    node.splitText(match.index + 5); // +5 is the length of the string to replace
    span.appendChild(node.splitText(match.index));
    node.parentNode.insertBefore(span, node.nextSibling);
});

Fiddle:

http://jsfiddle.net/QH5nG/5/

Replace text code found here:

https://stackoverflow.com/questions/1501007/how-can-i-use-jquery-to-style-parts-of-all-instances-of-a-specific-word#answer-1501213

2
  • It appears this method is breaking the controls in the Layer Slider plugin (wordpress.kreatura.hu/layersliderwp) I have checked the slider there are no instances of the site name in the slider text, file names or alt or title attributes. Mar 8, 2013 at 17:35
  • Correct, I forgot that jQuery's html() method strips script tags. I've updated with a non-jQuery solution that will keep the scripts in and not break the slider plugin. Mar 8, 2013 at 19:08
0

Search RegEx is a good plugin to be able to search and replace with Grep through all posts and pages. That way, you can add a CSS class to the text and style it anyway you want without the overhead or complexity of jQuery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.