Using the following code, I get a INDEX_SIZE_ERR: DOM Exception 1 error on the thisRange.setStart line. The code is meant to go through a whole page, find instances of the searchString, and then add a link in front of that search string. For example, if it finds 5 instances of the string, right now it will add the link in front of the first one but then error on the second and stop, leaving four words without the link. Any ideas?
if(searchString.length > 0) { // make sure the string isn't empty, or it'll crash.
// Search all text nodes
for(var i = 0; i < textNodes.length; i++) {
// Create a regular expression object to do the searching
var reSearch = new RegExp(searchString,'gmi'); // Set it to 'g' - global (finds all instances), 'm' - multiline (searches more than one line), 'i' - case insensitive
var stringToSearch = textNodes[i].textContent;
while(reSearch(stringToSearch)) { // While there are occurrences of the searchString
// Add the new selection range
var thisRange = document.createRange();
//alert((reSearch.lastIndex - searchString.length) + " <-> " + reSearch.lastIndex);
thisRange.setStart(textNodes[i], reSearch.lastIndex - searchString.length); // Start node and index of the selection range
thisRange.setEnd(textNodes[i], reSearch.lastIndex); // End node and index of the selection
var myLink = document.createElement('a');
var href = document.createAttribute('href');
myLink.setAttribute('href','http://www.google.com');
myLink.innerText ="GO";
thisRange.insertNode(myLink);
//theSelection.addRange(thisRange); // Add the node to the document's current selection
//thisRange.deleteContents();
}
}
}