JSFiddle - React, Tailwind, and code Playground

Caret Position functions

by nilloc

HTML

<content-editable-test contenteditable="" style="outline: 0px solid transparent;"><sub1><sub0>sub0</sub0>sub1.<sub2><sub3>sub3</sub3>sub2</sub2></sub1><br>
<sub4>123</sub4><sub3>su<br>
b2</sub3><br>
</content-editable-test>

JavaScript

document.body.onload = function(){
    console.log("setting cursor to 1,2");
    setCaretPosition(document.querySelector("content-editable-test"),1,2);
    setTimeout(function(){
    	setCaretPosition(document.querySelector("content-editable-test"),0,2);
      console.log('moved caret')
    }, 1000)
}
document.querySelector("content-editable-test").onclick = function(){
   
    console.log(getCaretPosition(this));
    
}


function previousRelative(element,root){
        
        if(element.previousSibling){
            return element.previousSibling;
        }
        else if(element.parentNode){
            if(element.parentNode==root){
               return undefined;
            }
            return previousRelative(element.parentNode,root);
        }
        else {
            return undefined;

        }
}
function nextRelative(element,root){
        if(element.nextSibling){
            return element.nextSibling;
        }
        else if(element.parentNode){
            if(element.parentNode==root){
               return undefined;
            }
            return nextRelative(element.parentNode,root);
        }
        else {
            return undefined;
        }
    }
function firstDescendant(element){
        if(!element.firstChild){ 
            return undefined;
        }
        else{
          while(element.firstChild){
            element=element.firstChild;
          }
          return element;
        }
}        
 


function setCaretPosition(contentEditableElement,row,col){
   function putCaret(el,offset) {
    contentEditableElement.focus();
    var range = document.createRange();
    var sel = window.getSelection();
    range.setStart(el, offset);
    //range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
   
    
}
   function visit(node){
         if(node.nodeType==1){
              //find text nodes as that's what we can set caret on
              let childNodes = node.childNodes;
              for(let...