Sourabh
Sourabh

Reputation: 1765

Get cursor parent in editable div

I have a content editable div which looks like this:

<div class="note" contenteditable="true">
   ABCD
   <div class="first">EFGH</div>
   <div class="second">IJKL</div>
   MNOP
</div>

So this makes the whole code editable. What I need to find out is, on every keypress, which element contains the cursor. So if the cursor is right after E, it should result the div with class first.

I tried using focus() event on the child divs, but it doesn't get fired when the parent is contenteditable.

Upvotes: 0

Views: 312

Answers (1)

toastrackengima
toastrackengima

Reputation: 8732

This should give you the element the caret (blinking text cursor) is currently in:

let caretElement = document.getSelection().anchorNode.parentNode;

Here's an example which highlights that element as you move around:

setInterval(()=>{
  let marked = document.querySelector(".marked");
  if (marked) {
      marked.classList.remove("marked");
  }
  
  let currentElement = document.getSelection().anchorNode;
  if (currentElement) {
    currentElement.parentNode.classList.add("marked");
  }
},200);
.marked {
  background-color:#f00;
}
<div class="note" contenteditable="true">
   ABCD
   <div class="first">EFGH</div>
   <div class="second">IJKL</div>
   MNOP
</div>

Upvotes: 1

Related Questions