0

If I add an event Listener on click I get the actual element clicked on, whether it's the element I added the listener to or a child element.

But if I do the same for input, keyup, keydown, or keypress on a content-editable element, I only get the element the event listener is added on, not child elements, even if the input happened in the child element.

How can I also get the child element when the key is pressed on it?

For instance: Click the word "Child" in the content-editable div below and type, and you'll see that e.target is the div, not the span:

document.getElementsByTagName("div")[0].addEventListener("click",function(e){
  document.getElementsByTagName("b")[0].innerHTML = e.target;
});
document.getElementsByTagName("div")[1].addEventListener("input",function(e){
  document.getElementsByTagName("b")[0].innerHTML = e.target;
});
Click:
<div>Parent
  <span>Child</span>
</div>
<br>
Input:
<div contenteditable>Parent
  <span>Child</span>
</div>
<br>

<div>Target:<b></b></div>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Drakeless
  • 31
  • 5
  • This is very interesting. `document.activeElement` is also the div, even when you're typing in the `span`. – T.J. Crowder Jul 08 '18 at 09:47
  • I was about to check getting the active selection when Mina found the duplicate -- which solves this with selection APIs. :-) – T.J. Crowder Jul 08 '18 at 09:48
  • https://stackoverflow.com/questions/6752708/how-to-detect-when-a-child-element-of-a-contenteditable-div-is-edited-via-keyboa – Mina Jul 08 '18 at 09:48
  • 1
    @T.J.Crowder Can't be more clear in the dupe, so deleted my answer :) – Asons Jul 08 '18 at 09:52

0 Answers0