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();
}
}
}
Once you've added a link, the document has changed. When you next call thisRange.setStart
, it's using the index from the original string, but setting it in the now changed document.
You need to add them in reverse order. Try storing the match indexes in an array, and then walk your array of indexes backwards to inject your links.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With