How to get the selected element inside a contenteditable element

喜欢而已 提交于 2019-12-04 14:06:30

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.

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