How to get the selected element inside a contenteditable element

[亡魂溺海] 提交于 2019-12-06 08:18:26

问题


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 :)


回答1:


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.



来源:https://stackoverflow.com/questions/34808447/how-to-get-the-selected-element-inside-a-contenteditable-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!