1

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);         
        }
    });
  }
0

1 Answer 1

0

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);
        }
    });
  }
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Matt! In my case, the previousSibling is also null, so it goes to parentNode.appendChild(newNode); However, I see bunch of mutation records being printed after made a text change, which are in the following sequence - Text node removed, span node added, remove text node under span, span node added and span node removed. The text I typed is getting moved automatically to a wrong position
Perhaps it's a lot more simple than I thought. you can insert the span, before the target, then add the target to the span.
Unfortunately, that gives the same behaviour. Here's the complete code that I am trying to run on w3school github.com/saurabhkulkarni26/testcode/blob/main/…
The editor is automatically removing the span from the DOM, so I don't think this is possible with the editor you are using.
You were right. The editor was the problem. I used a different editor and now it does not remove those nodes automatically. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.