Skip to content

Instantly share code, notes, and snippets.

@jdeisenberg
Created September 10, 2014 18:52
Show Gist options
  • Save jdeisenberg/f876f2dcc1c166b47cf3 to your computer and use it in GitHub Desktop.
Save jdeisenberg/f876f2dcc1c166b47cf3 to your computer and use it in GitHub Desktop.
Crawl through DOM to replace text content
<!DOCTYPE html>
<html xml:lang="en" lang="en"
xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Text Replacer</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
//<![CDATA[
function domReplacer(startNode, replaceFunction) {
textReplacer(startNode.firstChild, replaceFunction);
}
function textReplacer(node, replaceFunction) {
while (node != null)
{
if (node.nodeType == 3) { // TEXT_NODE
node.nodeValue = replaceFunction(node.nodeValue);
}
else if (node.nodeType == 1) { // ELEMENT_NODE
textReplacer(node.firstChild, replaceFunction);
}
node = node.nextSibling;
}
}
/*
Custom replace function that replaces all
lower case vowels with a question mark
*/
function vowelMystifier(str) {
return str.replace(/[aeiou]/gi, '?');
}
/*
Custom replace function that replaces all
lower case vowels with their upper case equivalent
*/
function vowelHighlighter(str) {
function goUp(match) {
return match.toUpperCase();
}
return str.replace(/[aeiou]/gi, goUp);
}
// ]]>
</script>
</head>
<body>
<div id="zorko">
<p>
This is a <em>simple <strong>archetype</strong> of a paragraph</em>
that has <a href="http://whatwg.org">a <dfn>link</dfn> in it</a>
in order to show the replacer function at work.
<!-- comments need not apply -->
</p>
</div>
<p>
<input type="button" value="Replace vowels with ?"
onclick="domReplacer(document.getElementById('zorko'), vowelMystifier)"/>
<input type="button" value="Uppercase vowels"
onclick="domReplacer(document.getElementById('zorko'), vowelHighlighter)"/>
</p>
<p>Note: you have to refresh the page after you click a button to restore it
to its original state.</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment