sabithpocker sabithpocker - 1 year ago 76
Javascript Question

Change all textNodes in a page

I am using the following script to change all the text in a page to a long text without spaces "aquickbrownfoxjumpedoveralazyfrog", this is to test if text is breaking gracefully in all places.

But when i run the script by pasting it in console, it somehow adds this text into different places randomly and oddly fills the page! Any idea on where I am doing wrong?

(function(el, string){
var n, a=[], walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
while(n=walk.nextNode()) n.nodeValue = string;
}(document.body, 'abigfoxjumpedoveralazyfrogmultipletimes'));

Answer Source

Remember that a text node may be just white space, or to put in another way white space is also a text node. Such nodes will be filled in by your script. This will result in your replacement text appearing in many unexpected places.

  <span>Hi bob</span>**THERE IS AN EMPTY TEXT NODE HERE**

Your result will thus be


To avoid this, test for the presence of any non-white-space character in the text node:

while (n=walk.nextNode()) if (/\S/.test(n.nodeValue)) n.nodeValue = string;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download