Adding different colors to each character in a sentence or word

Posted in: javascript by musiitwa joseph 2016-01-24 at 05:34:57

image for Adding different colors to each character in a sentence or word

The word or sentence is splitted in characters. A span element is added to each character. An inline style with a color property is added in the opening span tag, the value of the color property is a function call - threeHexa() which generates random a color whenever it is called.

The function call is called for all the characters.

This can look nice for children's sites


  1. When the color generated is the same as the background color or close to the background, the character may not be seen clearly or totally not seen.
  2. When the element which has the id contains other tags, the tags will also be affected.

Element to color

<h1 class="multiColored">Different colors</h1>


function _(idValue){
    return document.getElementById(idValue);

function __(classValue){
    return document.getElementsByClassName(classValue);

//3 hexadecimal random color generator
function threeHexa(){
    var i, colorCode="";
    //you change 3 to 6 in the for loop for 6 hexadecimal color codes
    for(i=0; i<3; i++){
        //.toString(16) converts a decimal to hexadecimal
        //Math.random generate a random number between 0 and 1
        //The number is multiplied by 16 to get number between 0 and 15
        //Math.floor rounds down the number eg 0.111 to 0 and 14.333 to 14
        colorCode += (Math.floor(Math.random()*16)).toString(16);
    return "#"+colorCode;    

window.onload = function(){
    var i,j,stringToColor,stringSplitted,output;
    var allElements = __("multiColored");
    for(i=0; i<allElements.length; i++){
        output = "";
        stringToColor = allElements[i].innerHTML;
        for(j=0; j<stringToColor.length; j++){
            output += '<span style="color:'+threeHexa()+'">'+stringToColor.charAt(j)+'</span>';
        allElements[i].innerHTML = output;