I am trying to make text changes based on when the user clicks the "bold" button using the Range and Selection Objects. When the text node is empty, the range that I have set using setStart() and setEnd() seems to not be working because the cursor does not move into the text node, but rather stays at its initial text node that is already given within my contenteditable div. However, If I add some preexisting content to the text Node, the range is correct,the cursor moves into the newly-created text node, and the content is bold as well as my additional input. So how do I get the cursor to go into the text Node without any content? Thanks.
Here is a code snippet:
function setBold() {
let parent = document.querySelector('.current'); /*contenteditable parent element*/
let sel = window.getSelection();
let selRange = s.getRangeAt(0);
let bold = document.createElement('b');
let range = document.createRange();
/*if the node has content this solution works, but in this example it does not currently*/
let node = document.createTextNode("");
parent.appendChild(node);
range.setStart(node,0);
range.setEnd(node,node.length);
range.surroundContents(bold);
sel.removeAllRanges();
sel.addRange(range);
}