Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
129
rated 0 times [  130] [ 1]  / answers: 1 / hits: 17769  / 15 Years ago, wed, july 29, 2009, 12:00:00

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.


More From » dom

 Answers
11

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);
}

[#99041] Thursday, July 23, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elishaannac

Total Points: 28
Total Questions: 97
Total Answers: 101

Location: Samoa
Member since Mon, Nov 8, 2021
3 Years ago
elishaannac questions
Sun, Dec 5, 21, 00:00, 3 Years ago
Mon, Jun 14, 21, 00:00, 3 Years ago
Mon, Jul 22, 19, 00:00, 5 Years ago
Mon, Jul 8, 19, 00:00, 5 Years ago
;