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>
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.
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?