Skip to content

Instantly share code, notes, and snippets.

@lebbe
Created September 6, 2013 14:01
Show Gist options
  • Save lebbe/6464236 to your computer and use it in GitHub Desktop.
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.
<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