38

Let's say I have some HTML code like this:

<body contentEditable="true">
   <h1>Some heading text here</h1>
   <p>Some text here</p>
</body>

Now the caret (the blinking cursor) is blinking inside the <h1> element, let's say in the word "|heading".

How can I get the element the caret is in with JavaScript? Here I would like to get node name: "h1".

This needs to work only in WebKit (it's embedded in an application). It should preferably also work for selections.

vsync
  • 118,978
  • 58
  • 307
  • 400
Lucas
  • 6,328
  • 8
  • 37
  • 49

1 Answers1

64

Firstly, think about why you're doing this. If you're trying to stop users from editing certain elements, just set contenteditable to false on those elements.

However, it is possible to do what you ask. The code below works in Safari 4 and will return the node the selection is anchored in (i.e. where the user started to select, selecting "backwards" will return the end instead of the start) – if you want the element type as a string, just get the nodeName property of the returned node. This works for zero-length selections as well (i.e. just a caret position).

function getSelectionStart() {
   var node = document.getSelection().anchorNode;
   return (node.nodeType == 3 ? node.parentNode : node);
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536
You
  • 22,800
  • 3
  • 51
  • 64
  • I'm not trying to block the user in any way, I really just need the name of the node so I can update a part of the UI. Thank you for providing the answer, this works great. – Lucas Jul 31 '09 at 11:58
  • 5
    `node.nodeType == 3` would be a better check for a text node. – Tim Down May 19 '11 at 11:43
  • Using this in a JavaFX HTMLEditor this works nicely returning the element where the cursor / text caret is placed in a contentEditable section, thanks! As a side note, document.activeElement is recognised but always returns the body element which isn't very helpful. – T-and-M Mike Dec 08 '12 at 22:59
  • You should use [`window.getSelection`](https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection) and not [`document`](https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/getSelection) which is better in most cases – vsync Dec 06 '19 at 12:25
  • 1
    `window.getSelection().baseNode` will also work. [Related thread](https://stackoverflow.com/q/27241281/104380) – vsync Dec 06 '19 at 12:28