Unknown Coder
Unknown Coder

Reputation: 6741

Italicize a word every time it appears on a page?

I have a web page for the Podunk company. But every time Podunk appears on the page (no matter where it is) it needs to be shown as Podunk!

Note that this is ANYWHERE on the page so it could be in header tags, list tags, in multiple nested DIVs, etc.

What is the best way to go about this? I'm thinking that jQuery is the better solution (as opposed to CSS) but I don't know how to go about it? Can someone please provide a code snippet for this kind of replacement on an entire page element.

Upvotes: 1

Views: 322

Answers (2)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201896

If it needs to appear in italics, the absolute surest way is to use <i>Podunk</i> and to make the best effort to ensure that the font family used has an italic typeface.

It is a misguided aim anyway, so you should not worry about colleagues saying that the i markup is not “semantic”. But you might consider using <i class=company>Podunk</i>, just to make it easier to drop such use of italic without dropping sensible uses of italic, should the client come to their senses.

Upvotes: 1

major-mann
major-mann

Reputation: 2652

My original answer was incorrect (as pointed out in the comment :) ) I have edited this answer to include the correct solution.

var rgx = /Podunk/g;
$("body *")
    .contents()
    .filter(function() {
        if (this.nodeType !== 3){
            return false;
        }
        return true;
    })
    .each(function(){
        var $this = $(this);
        var txt = $this.text();
        if (rgx.test(txt)){
            $this.replaceWith("<span>" + txt.replace(rgx,"<span class='podunk'>Podunk</span>") + "</span>");
        };
    });​

This has the downside that any element that has only Podunk in it gets and additional span element. ie, if you have

<a>Podunk</a> 

you end up with

<a><span><span class="podunk">Podunk</span></span>. 

I think with a little consideration this could be overcome.

Upvotes: 1

Related Questions