Используя следующий код, я получаю ошибку INDEX_SIZE_ERR: DOM Exception 1 в строке thisRange.setStart. Код предназначен для просмотра всей страницы, поиска экземпляров searchString и добавления ссылки перед этой строкой поиска. Например, если он найдет 5 экземпляров строки, прямо сейчас он добавит ссылку перед первым, но затем ошибку на втором и остановится, оставив четыре слова без ссылки. Есть идеи?
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();
}
}
}