Skip to content

Instantly share code, notes, and snippets.

@icio
Created November 29, 2010 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save icio/720026 to your computer and use it in GitHub Desktop.
Save icio/720026 to your computer and use it in GitHub Desktop.
spanChars
function spanChars(e)
{
if (!e) e = document.body;
// Replace the text node with a span for each letter it consists of
if (e.nodeType == document.TEXT_NODE)
{
var text = e.nodeValue;
for (var c = 0; c < text.length; c++)
{
// Create the span element around the letter
var span = document.createElement("span");
span.className = "letter";
span.appendChild(document.createTextNode(text.charAt(c)));
// Put the span in before the text node
e.parentNode.insertBefore(span, e);
}
// Remove the original text node (we can now consider it replaced)
e.parentNode.removeChild(e);
}
// Otherwise check the child nodes
else {
for (var c = e.childNodes.length-1; c >= 0; c--) {
spanChars(e.childNodes[c]);
}
}
}
window.onload = function()
{
var h2 = document.getElementsByTagName("h2");
for (var i = 0; i < h2.length; i++)
{
spanChars(h2[i]);
console.log(h2[i]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment