I want to add a background color for each letter within this range.
Using an array of colors:
Live demo
var myColors = ["#cf5", "green", "purple", "blue"]; // YOU CAN ADD MORE COLORS! $('.kkcountdown-box').find('span').each(function(){ var $el = $(this), text = $el.text(), len = text.length, coLen = myColors.length, newCont = ''; for(var i=0; i<len; i++){ newCont += '<span style="background:'+ myColors[i%coLen] +'">'+ text.charAt(i) +'</span>'; } $el.html(newCont); });
The above will, wrapping each individual letter in a separate span , will also add the background color from your Array color list.
As soon as the end of the color list is reached, it will start from the first, etc.
Using random color:
Live demo
$('.kkcountdown-box').find('span').each(function(){ var $el = $(this), text = $el.text(), len = text.length, newCont = ''; for(var i=0; i<len; i++){ var bgColor= '#'+ (Math.random() * 0xffffff).toString(16).substr(-6); newCont += '<span style="background:'+bgColor+'">'+ text.charAt(i) +'</span>'; } $el.html(newCont); });
The above information will receive every letter inside the <span> and transfer it to a new span with a randomly created background color.
source share