I\'m trying to write a script in jQuery that would iterate through each text element inside a page. Then I need to change the color of each letter one by one. For example, f
<span>
elementDocumentFragment
// jQuery plugin, example:
(function($) {
$.fn.styleTextNodes = function() {
return this.each(function() {
styleTextNodes(this);
});
};
})(jQuery)
function styleTextNodes(element) {
var span = document.createElement('span');
span.className = 'shiny-letter';
// Recursively walk through the childs, and push text nodes in the list
var text_nodes = [];
(function recursiveWalk(node) {
if (node) {
node = node.firstChild;
while (node != null) {
if (node.nodeType == 3) {
// Text node, do something, eg:
text_nodes.push(node);
} else if (node.nodeType == 1) {
recursiveWalk(node);
}
node = node.nextSibling;
}
}
})(element);
// innerText for old IE versions.
var textContent = 'textContent' in element ? 'textContent' : 'innerText';
for (var i=text_nodes.length-1; i>=0; i--) {
var dummy = document.createDocumentFragment()
, node = text_nodes[i]
, text = node[textContent], tmp;
for (var j=0; j<text.length; j++) {
tmp = span.cloneNode(true); // Create clone from base
tmp[textContent] = text[j]; // Set character
dummy.appendChild(tmp); // append span.
}
node.parentNode.replaceChild(dummy, node); // Replace text node
}
}