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

205
Views
Formatting of a selected text cannot be undone

I have a problem with my custom WYSIWYG editor.

document.getElementById('bold').addEventListener('click', () => edit('STRONG'));
document.getElementById('italic').addEventListener('click', () => edit('EM'));

function edit(format) {
  const parentElementOfSelectedText = document.getSelection().getRangeAt(0).commonAncestorContainer.parentElement;

  // If element is already formatted, undo the format
  if (parentElementOfSelectedText.tagName === format) {
    let grandParentOfSelectedText = parentElementOfSelectedText.parentElement;
    if (parentElementOfSelectedText.textContent) {
      const selectedText = document.createTextNode(parentElementOfSelectedText.textContent);
      grandParentOfSelectedText.insertBefore(selectedText, parentElementOfSelectedText);
      grandParentOfSelectedText.removeChild(parentElementOfSelectedText);
      grandParentOfSelectedText.normalize();
    }
  } else {

    const selectedText = document.getSelection().getRangeAt(0);
    const node = document.createElement(format);
    const fragment = selectedText.extractContents();

    if (fragment) {
      node.appendChild(fragment);
    }
    selectedText.insertNode(node);
  }

}
<button id="bold">B</button>
<button id="italic">I</button>

<p>Lorem ipsum</p>

This is how it works:

Select a text and click on a button. The text will be formatted. Unselect the same text and select it again. Now click again on the same button to remove the format.

This is how it does NOT work:

Select a text and click on a button. The text will be formatted. Now click again on the same button to remove the format.

I assume, that it probably doesn't work, because I am inserting an element inside the parent element. So at this moment, this element is not selected. With selectedText?.selectNode(node) I have tried to select the correct node but this doesn't change anything.

So how can I remove the format, when the text stays selected?

about 4 years ago · Juan Pablo Isaza
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!