Replace mutation target text node with a span element

427 Views Asked by At

I am using MutationObserver to track character changes in my rich text editor. Everytime a text is edited, the mutation callback method is called with the list of mutation records. The mutation target is the text node in which changes are made. I want to wrap this text node with a span so that I can use some css to highlight changed text. However, this is not working for me. Can you please guide what am I doing wrong here?

function callback(mutations) {
    mutations.forEach(function(mutation){
        if(mutation.type == 'characterData'){
           let parentNode = mutation.target.parentElement;

           // Create the new node to insert
           let newNode = document.createElement("span");
           newNode.classList.add('change-highlighter');

           // appending existing text node to new span element
           newNode.appendChild(mutation.target);

           // inserting newNode before text node
           parentNode.insertBefore(newNode, mutation.target);         
        }
    });
  }
1

There are 1 best solutions below

5
Matt Ellen On BEST ANSWER

I would insert the span, then append the target.

function callback(mutations) {
    mutations.forEach(function(mutation){
        if(mutation.type == 'characterData'){
           let parentNode = mutation.target.parentElement;

           // Create the new node to insert
           let newNode = document.createElement("span");

           newNode.classList.add('change-highlighter');

           // inserting newNode before text node
           parentNode.insertBefore(newNode, mutation.target);

           // appending existing text node to new span element
           newNode.appendChild(mutation.target);
        }
    });
  }