Pepijn Gieles
Pepijn Gieles

Reputation: 727

How to get the selected element inside a contenteditable element

What I've tried

I checked out this question, and this one, the problem is it gives me the content of the current selection, but I want the dom element instead.


What I want to do

I'm looking for a way to get the tagname of an element that is currently being edited with javascript. For example:

<article contenteditable=true>
    <h2>Some List</h2>
    <ul>
        <li>Item 1</li>
        <li>Item *caret here* 2</li>
        <li>Item 3</li>
    </ul>
</article>

I want to be able to put the list item into a javascript el variable. So I that I can do for example:

el.tagName
el.className

Does anyone know how to achieve this? Tx :)

Upvotes: 6

Views: 3355

Answers (1)

raxell
raxell

Reputation: 677

You can use a Range to refer to the selected part of the document and than check the commonAncestorContainer for retriving the <ul>.
In your example if you select part of the list you can retrieve the <ul> with something like:

    var sel = window.getSelection();
    var range = sel.getRangeAt(0);
    var ulTag = range.commonAncestorContainer;

If you instead want to get the element pointed by the cursor (without there being a selection) you can refer to the startContainer property and than check the parentNode for retriving the <li>. For example:

    var sel = window.getSelection();
    var range = sel.getRangeAt(0);
    var pointedLiTag = range.startContainer.parentNode;

Please note that those are just simple use cases, in real documents there's lots of nested elements, so you must ensure that the element you retrieve is the one you expect before using it.

Upvotes: 13

Related Questions