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

Member Avatar for fatihpiristine

use string replace instead of regex

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.