Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

285
Views
Get and Set Caret in nested contenteditable Div element TypeScript (or JavaScript)

I am trying to track and restore the caret position inside nested contentEditable div my code will be like.

<div id="parentDiv" contentEditable={"true"}>
   <div id="chip-1" styles={color: "red",border: "1px solid #999",border-radius: "10px",margin-right: "5px",padding: "3px"}>
     TotalCurrentRatio
   </div>
  <div id="chip-2" styles={color: "red", margin-right: "5px",padding: "3px"}>
   /
  </div>
  <div id="chip-3" styles={color: "red",border: "1px solid #999",border-radius: "10px",margin-right: "5px",padding: "3px"}>
   NetAsset
  </div>
</div>

<button id="button" onClick={setCaret}>
    GetCaret
</button>
<button id="FoucsButton" onClick={focusEnd}>
    setCaret
</button>

I am trying to make two functions

  1. GetCaret: which save current postion of caret in a variable.

  2. SetCaret: which sets the position of character based on postion returned by the GetCaret I had tried many solutions like

    const GetCaret= (
     containerEl: EventTarget & HTMLDivElement
     ) => {
     var range = window.getSelection()!.getRangeAt(0);
     var preSelectionRange = range.cloneRange();
     preSelectionRange.selectNodeContents(containerEl);
     preSelectionRange.setEnd(range.startContainer, range.startOffset);
     var start = preSelectionRange.toString().length;
    
     return {
       start: start,
       end: start + range.toString().length,
     };
    };
    

2.SetCaret

   const setCaret = (
    caretPosition: {
      start: number;
      end: number;
    }
   ) => {
   var el = document.getElementById("parentDiv");
   var range = document.createRange();
   var sel = window.getSelection();
   if (el !== null && sel !== null && el.innerText.length > 0) {
      range.setStart(el, 4314);
      range.collapse(true);
      console.log("setCaret ", caretPosition.end);
      sel.removeAllRanges();
      sel.addRange(range);
      el.focus();
   }
  return;
 };

But it is not working for nested contentEditable div(as shown above) screenshot of my component: enter image description here

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!