How to change every other letter’s font color?

I’m trying to create a Christmas user group on my forums, and would like to replace the users name with a green/red pattern using JavaScript. So basically, JavaScript would turn every other letter within a specific CSS class into green, and the others would stay red.

So this is what it looks like now:

<span class="style6">Username</span>

I’d like JavaScript to turn it into something like this:

<span class="style6">
    <span class="color_red">U</span>
    <span class="color_green">s</span>
    <span class="color_red">e</span>
    <span class="color_green">r</span>
    <span class="color_red">n</span>
    <span class="color_green">a</span>
    <span class="color_red">m</span>
    <span class="color_green">e</span>
</span>

Answer

As long as your <span> doesn’t contain any HTML you could do this.

$('.style6').each(function(){
    var letters = $(this).text().split('');
    $(this).text('');
    for(var i = 0; i < letters.length; i++){
        if(i % 2 == 0){
            $(this).append('<span class="color_red">' + letters[i] + '</span>');
        }
        else{
            $(this).append('<span class="color_green">' + letters[i] + '</span>');
        }
    }
});

It would be a bit more complicated if your <span> did contain HMTL.

Edit: This is with jQuery BTW. Not sure if that is OK.

Leave a Reply

Your email address will not be published. Required fields are marked *