vegUI.org home of the javascript based window manager and AJAX framework

Replacing characters throughout the page

written by vegu on 31 Dec, 2006 01:58:53
A member over at CodingForums had a problem where he needed to replace certain characters in his page using javascript.

I usually dont copy the stuff i post over at coding forums to this page, but here is one solution to his problem.

We create a function that allows us to recursively loop through all the elements on the page. We will call this function scanNodes.

Code: Javascript
function scanNodes(node) {

var i;

if(node.nodeName == '#text') {

/* get the old text held by the text node */

var oldText = node.nodeValue;

/* create a new text node with the characters replaced, in the case below
* the character a is replaced by A
*/


var newNode = document.createTextNode(oldText.replace(/a/g, 'A'));

/* insert the new node before the old node, to assure it will be in the correct spot */

node.parentNode.insertBefore(newNode, node);

/* remove the old node */

node.parentNode.removeChild(node);

/* bail since text nodes dont have children */

return;
}

/* recursively loop through all child nodes */

for(i = 0; i < node.childNodes.length; i++)
scanNodes(node.childNodes[i]);
}


In order to get the replacement process started simply call the scanNodes function on the body element when the page has loaded.
Code: HTML
<body onload="scanNodes(document.body);">

Related Posts

  • No related posts



Your Comment

name:*
email-address:

Are you human?



Comments

No comments yet.