Created
January 19, 2015 13:24
-
-
Save m1el/df2a9a6755d3fde7e9b3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// wrap first text letter of an element with a span having a specified class | |
// red letter | |
// License=WTFPLv2 | |
function redLetterize(element, cls) { | |
cls = cls === undefined ? 'first-letter-wrapped' : ('' + cls).replace(/^\s+|\s+$/g, ''); | |
while (element.firstChild && element.firstChild.tagName) { | |
if ((' ' + element.firstChild.className + ' ').indexOf(' ' + cls + ' ') > -1) { | |
return; | |
} | |
element = element.firstChild; | |
} | |
if (element.firstChild && element.firstChild.nodeType === document.TEXT_NODE) { | |
var text = ('' + element.firstChild.data).replace(/^\s+|\s+$/g, ''), | |
span, textEl, | |
firstCode = text.length && text.charCodeAt(0), | |
charLen = firstCode >= 0xD800 && firstCode < 0xDC00 ? 2 : 1; | |
if (!text.length) { | |
return; | |
} | |
span = document.createElement('span'); | |
span.appendChild(document.createTextNode(text.substr(0, charLen))); | |
span.className = cls; | |
element.firstChild.data = text.substr(charLen, text.length); | |
element.insertBefore(span, element.firstChild); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment