Created
September 6, 2013 14:01
-
-
Save lebbe/6464236 to your computer and use it in GitHub Desktop.
Just some javascript which wraps a span-element around all text nodes within a given node. This is not useful in itself, but is a skeleton for future javascript which want to convert text on a page some way or another. Only tested in chrome for now.
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
<script type="text/javascript"> | |
"use strict"; | |
function changeAll() { | |
wrapSpan( | |
document.getElementsByTagName('body')[0], 0 | |
); | |
} | |
/** | |
* Wrap a span element around all text nodes. | |
**/ | |
function wrapSpan(node, index) { | |
if(node.nodeName === '#text') { | |
var text = node.textContent; | |
var s = document.createElement('span'); | |
s.textContent = text; | |
node.parentElement.insertBefore(s, node.parentElement.childNodes[index]); | |
node.remove(); | |
} else { | |
var length = node.childNodes.length; | |
// childNodes is a collection, not an array. :-/ | |
for(var i = 0; i < length; i++) | |
wrapSpan(node.childNodes[i], i); | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment