0

Hi all,

The following script is a task I set myself to learn javascript, essentially there are several arrays containg keywords which, depending on the array, should highlight those words in different colours.

The code works but I get an unresponsive script error and it's very slow. I think because of the document.body innerhtml part as I tried keyword swaps and it was fine.

var textnodes = document.evaluate( "//body//text()", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
	
	for (var i = 0; i < textnodes.snapshotLength; i++)
	{
		node = textnodes.snapshotItem(i);
		node.data = highlight(node.data);
	}

function highlight()
	  {		
		for (var j = 0; j < testArrayOne.length; j++)
        {
		document.body.innerHTML = document.body.innerHTML.replace(new RegExp(testArrayOne[j]),'<span style="color:#ff0000">' + testArrayOne[j] + '</span>');	
		}
		
		for (var j = 0; j < testArrayTwo.length; j++)
        {
		document.body.innerHTML = document.body.innerHTML.replace(new RegExp(testArrayTwo[j]),'<span style="color:#FF00FF">' + testArrayTwo[j] + '</span>');	
		}
		
	  }

Thanks for your help.

P.S. this is a userscript for greasemonkey

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by Cotillion
0

use string replace instead of regex

0

use string replace instead of regex

Thanks for the reply.

I assumed you meant like this;

document.body.innerHTML = document.body.innerHTML.replace(String.replace(testArrayOne[j]),'<span style="color:#ff0000">' + testArrayOne[j] + '</span>');

which is still slow. any thoughts?

Thanks

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.