I'm working with a contenteditable and trying to create a simple editor. Unfortunately I cannot use document.execCommand() and have to implement it myself. What I'm trying to do here, is that if user presses the bold button, I want to make the text bold. The code I have written below works, but it only works when the selection is in one node, not multiple nodes.
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 contenteditable="true" id="div">This is the editor. If you embolden only **this**, it will work. But if you try to embolden **this <i>and this**</i>, it will not work because they are in different nodes</div>
<button id="bold">Bold</button>
My question is: Is there a solution where I can click bold and it can embolden the text even if they are in different nodes? If so, how can I do this? I'm looking for something simple and elegant, but if it has to be complex, I would appreciate some explanation of the code. Thanks a lot.