如何在 contenteditable 元素中获取所选元素

How to get the selected element inside a contenteditable element

我试过的

我检查了 this question, and this one,问题是它给了我当前选择的内容,但我想要 dom 元素。


我想做什么

我正在寻找一种方法来获取当前正在使用 javascript 编辑的元素的标记名。例如:

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

我希望能够将列表项放入 javascript el 变量中。所以我可以做例如:

el.tagName
el.className

有人知道如何实现吗?发送:)

您可以使用 Range to refer to the selected part of the document and than check the commonAncestorContainer 来检索 <ul>
在您的示例中,如果您 select 列表的一部分,您可以使用类似以下内容的 <ul> 检索:

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

如果您想获取光标指向的元素(没有 selection),您可以参考 startContainer 属性 然后检查 parentNode 用于检索 <li>。例如:

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

请注意,这些只是简单的用例,在实际文档中有很多嵌套元素,因此在使用之前,您必须确保检索到的元素是您期望的元素。