How to set caret line number and position in contenteditable div

I am attempting to reset the caret to its original position in a contenteditable div after injecting HTML tags into the div’s innerHTML.

I’ve seen similar threads on here but have run into issues using code I found and struggle to debug because I don’t really understand selection or range objects. Would really appreciate some help.

Here is my current attempt:

const highlighting = () => {
  let sel = window.getSelection();
  let pos = sel.getRangeAt(0).startOffset
  code.innerHTML = code.innerText.replaceAll(/(d+)/g, `<number>$1</number>`);
  let range = document.createRange();
  range.setStart(code.childNodes[currentLineNumber - 1], pos);
  range.collapse(false);
  sel.removeAllRanges();
  sel.addRange(range);
}

I think I found something that almost worked but didn’t work for multi-line editing or something.

Would really, really appreciate some help getting this right so I can focus on the actual syntax highlighting.

My goal is to be able to do something like moveCaret(lineNumber, position)