Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

206
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda