I'm working on a simple text editor using contenteditable in javascript. Unfortunately, I cannot use document.execCommand and have to implement it myself. I have created a function that makes my text bold. Here is the function:
document.getElementById("bold").onclick = function() {
var selection = document.getSelection(),
range = selection.getRangeAt(0).cloneRange();
range.surroundContents(document.createElement("b"));
selection.removeAllRanges();
selection.addRange(range);
}
<div id="editor" contenteditable="true">This is the contenteditable</div>
<button id="bold">Bold</button>
Now, when the user clicks on the bold button when the text is already bold, I want to unembolden the text. In other words, i want the text to not be bold anymore.
How can i do this? Is there like any opposite of range.surroundContents or something like that?
Note that I would like only the selected text to unbold and not every bold text in the document so jQuery's unwrap() will probably not work. I'm looking for a Vanilla js solution and something that's elegant and simple, but if it has to be complicated, I would appreciate some explanation of the code. Thank you very much.