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.
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.
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.
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.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With