sabithpocker sabithpocker - 1 month ago 7
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

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.

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

Your result will thus be

<div>abigfoxjumpedoveralazyfrogmultipletimes
  <span>abigfoxjumpedoveralazyfrogmultipletimes</span>abigfoxjumpedoveralazyfrogmultipletimes
</div>

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;
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^