0

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'));
sabithpocker
  • 15,274
  • 1
  • 42
  • 75
  • 1
    Basic debugging: `while(n=walk.nextNode()) console.log(n.nodeValue)` –  Oct 28 '16 at 17:23

2 Answers2

3

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

Are you expecting SHOW_TEXT to give you just visible text? My intuition here is that there is a disconnect between how you expect SHOW_TEXT to select and how it does.

Unfortunately, the MDN docs on this are lacking in concrete examples.

Here's a stack overflow answer that might explain what is happening: What Is A Text Node, Its Uses? //document.createTextNode()

It seems that elements may have multiple children that are text nodes. I'm not sure what the HTML you're parsing looks like, but you may have multiple text nodes that are all getting set to the same string.

Community
  • 1
  • 1
Wren
  • 65
  • 7
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/14129142) – ifixthat Oct 28 '16 at 21:05
  • I believe the paragraph after the link does include the essential parts of the answer? – Wren Oct 28 '16 at 23:04
  • @D.Ulick you probably want to give a code example if you want to avoid "link only deletion" – Tibrogargan Oct 30 '16 at 03:43