Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript INDEX_SIZE_ERR: DOM Exception 1 Error for ranges

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();
        }
    }
}
like image 353
joshholat Avatar asked Oct 14 '10 21:10

joshholat


1 Answers

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.

like image 105
gilly3 Avatar answered Oct 21 '22 16:10

gilly3