Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element node at caret position (in contentEditable)

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.

like image 618
Lucas Avatar asked Jul 29 '09 00:07

Lucas


People also ask

How do I get a caret position?

You also need the input's selectionDirection to get the caret position whenever selectionDirection is backward i.e. you make a selection left-ward in the textbox so that selectionStart is the caret, but when selectionDirection is forward the caret will be at selectionEnd.

How do you set a caret cursor position in Contenteditable element div?

To set caret position at a specific position in contenteditable div with JavaScript, we select the text node that with the text we want the cursor to be at and set the caret position there. to add a contenteditable div. Then we write: const node = document.

How do you get the caret position in an editable div?

To get contentEditable caret position with JavaScript, we change the selection to start from the beginning and then get the length of the full selected string. const cursorPosition = () => { const sel = document. getSelection(); sel.

What is a caret position?

In computing, caret navigation (or caret browsing) is a kind of keyboard navigation where a caret (also known as a 'text cursor', 'text insertion cursor', or 'text selection cursor') is used to navigate within a text document.


1 Answers

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); } 
like image 90
You Avatar answered Sep 24 '22 22:09

You