As others have pointed out, you can only stylize something that is an element, so you need to wrap each letter in its own element. Here is an example of how to do this. It also works recursively, so this will work with text that contains other elements, such as <b>, <a>etc. Other examples below assume that the div will only have text and other HTML tags inside.
var colours = Array("#ddd", "#333", "#999", "#bbb");
$('#header').hover(function(){
wrapLetters(this);
$('.random-color', this).css('color', function(){
var idx = Math.floor(Math.random() * colours.length);
return colours[idx];
});
}, function(){
$('.random-color', this).css('color', '#ddd');
});
function wrapLetters(el){
if ($(el).hasClass('random-color')) return;
$.each($.makeArray(el.childNodes), function(i, node){
if (node.nodeType !== Node.TEXT_NODE) return wrapLetters(node);
$.each(node.data, function(j, letter){
var span = $('<span class="random-color">').text(letter);
node.parentElement.insertBefore(span[0], node);
});
node.parentElement.removeChild(node);
});
}
Fiddle: http://jsfiddle.net/aWE9U/2/
source
share