0

i am trying to add spans to specific index in innerHtml of page

when i replace the old innerHtml with the new one > all the events in the page don't work

then i realize that the innerHtml make the events don't work >>

so how i can make this operation without loosing the events in the page ?

here is my code : -


var startInd = [50]; //the index of word in innerHtml

var lastInd = [55];  //the last index of word in innerHtml(its length)(the spanned area)

var str = document.body.innerHTML;

var count = 1;


for (let j = 0; j < count; j++) // count always 1
{
    let pre = str.substring(0, startInd[j]); // all html elements before the word
    let post = str.substring(lastInd[j], str.length); // all html elements after the word
    let phrase = str.substring(startInd[j], lastInd[j]); // the word

    let nextPhrase;

    if (j < count - 1) 
    {
        nextPhrase = str.substring(startInd[j + 1], lastInd[j + 1]);
    }

    str = pre + `<span id="myHeader${i}">${phrase}</span>` + post; // make the new innerHtml
    newID = "myHeader" + i;

    if (j < count - 1) 
    {
        startInd[j + 1] = str.indexOf(nextPhrase, startInd[j + 1]) - 1;
        lastInd[j + 1] = startInd[j + 1] + nextPhrase.length;
    }

    document.body.innerHTML = str
}

  • I see two ways to go about your problem, both involve not using `.innerHTML` after the first time, because it's destructive which makes it very difficult to reuse. Add HTML with JS in a [mcve] so I don't have to and I'll show you both ways. – zer00ne May 27 '22 at 18:55
  • You're going to need to use DOM functions to find and replace the specific text node that contains that word. I asked a [different but related question years ago](https://stackoverflow.com/questions/31275446/how-to-wrap-part-of-a-text-in-a-node-with-javascript) and received a really good answer you may want to look into. – Domino May 27 '22 at 18:58
  • If you actually obtained these indices by searching in `document.innerHTML`, it may be easier to just iterate over the document's descendants and search every text node for the word instead. Working from the HTML code position is going to be harder. – Domino May 27 '22 at 19:03

0 Answers0