views:

536

answers:

1

Hi,

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 name of the element the caret is in with JavaScript? Here I would like to get "h1".

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

If this is truly trivial, I apologize. My knowledge of JavaScript (and DOM) is sorely lacking.

+2  A: 

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;
    var startNode = (node.nodeName == "#text" ? node.parentNode : node);
    return startNode;
}
You
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