Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

209
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda