My current code allows for text to be bolded and unbolded using Window.getSelection(). I found the initial solution here: Bold/unbold selected text using Window.getSelection()
It works perfectly without any issues. However, when I tried to modify the code to only select text within a specific div with an id, I came across this solution: How to getSelection() within a specific div?
Upon combining both solutions, I noticed that the text was always bolded and never unbolded.
Here is my code snippet:
function addBold(){
// validate selection inside specified div
if(window.getSelection().baseNode.parentNode.id !== "editor") return;
const selection = window.getSelection().getRangeAt(0);
let selectedParent = selection.commonAncestorContainer.parentElement;
let mainParent = selectedParent;
if(selectedParent.closest("b")) {
var text = document.createTextNode(selectedParent.textContent);
mainParent = selectedParent.parentElement;
mainParent.insertBefore(text, selectedParent);
mainParent.removeChild(selectedParent);
mainParent.normalize();
} else {
const span = document.createElement("b");
span.appendChild(selection.extractContents());
selection.insertNode(span);
mainParent.normalize();
}
if (window.getSelection) {
if (window.getSelection().empty) {
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) {
window.getSelection().removeAllRanges();
}
} else if (document.selection) {
document.selection.empty();
}
};
<div id="editor" contenteditable="true">
You are the programmers of the future
</div>
<button onclick="addBold()">Bold</button>
Combining the two answers resulted in always bolding the text and ignoring the unbold functionality. Deleting the first line of the validation condition: if(window.getSelection().baseNode.parentNode.id resolved the issue and allowed for successful bolding and unbolding of text.