Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

107
Views
Replace mutation target text node with a span element

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);         
        }
    });
  }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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);
        }
    });
  }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!