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

128
Views
Set cursor position to 0 in inline node in HTML editable content

In an editableContent div I want the user to type something within an inline element. Therefore, when the cursor is within this inline element, and the user uses the left arrow key, the cursor should jump to position 0 WITHIN the inline element.

Here is an example:

document.querySelector("#editable").addEventListener("keydown", (e) => {
  const keys = ["ArrowLeft", "ArrowRight"]
  if (keys.includes(e.code)) {
    // handle event

    const selection = document.getSelection()
    if (!selection || !selection.anchorNode) {
      return
    }
    if (selection.anchorNode.parentElement.nodeName !== "MARK") {
      return
    }

    e.preventDefault()

    const setOffset = offset => {      
      const range = document.createRange()
      range.collapse()
      range.setStart(selection.anchorNode, offset)
      
      selection.removeAllRanges()
      selection.addRange(range)
    }



    if (e.code === keys[0]) {
      setOffset(0)

    }

    if (e.code === keys[1]) {
      setOffset(selection.anchorNode.textContent.length)
    }
  }

})
#editable {
  border: 1px solid black;
  padding: 10px;
}
<div id="editable" contentEditable>
  Here is some <mark>text</mark> for testing!
</div>

The problem is that setOffset(0) sets the cursor before the <mark> tag and typing there makes the text appear not within the <mark> tag.

On the other side using the right arrow and setting the cursor to the last element setOffset(selection.anchorNode.textContent.length) works as expected (typing there extends the mark tag).

Is there a trick to set the cursor to position 0 within the inline element?

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!