最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Determine which DOM elements the current text selection contains - Stack Overflow

programmeradmin1浏览0评论

I want to be able to find out which DOM elements are present in the text currently selected by the user in the browser.

document.getSelection() would get us the currently selected text. But how can we determine which DOM elements are contained in this text selection?

I want to be able to find out which DOM elements are present in the text currently selected by the user in the browser.

document.getSelection() would get us the currently selected text. But how can we determine which DOM elements are contained in this text selection?

Share Improve this question asked Mar 27, 2010 at 12:49 sonofdelphisonofdelphi 2,0366 gold badges20 silver badges26 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

window.getSelection() gives you a Selection object. Use selection.rangeCount and selection.getRangeAt() to get a Range object representing which selection you want.

Now you can get the first and last nodes in the selection from range.startContainer/startOffset and range.endContainer/endOffset. You could then walk up and down the tree to pick up all the elements in between those two positions, eg. using the getElementsBetweenTree() function from this answer.

Unfortunately, IE's TextRange model is totally different to the W3 and HTML5 standard, and in general much worse. It does't give up the start and end positions nearly as easily, and not in any reliable way. All you get is parentElement to tell you the mon ancestor, and from there you're limited to guessing where the range is based on creating a new Range and calling moveToElementText on it then pareEndPoints with the selection range. And if you need to know the exact text selection you're then guessing based on moveStart/moveEnd​ing the range and paring, which isn't fun at all.

containsNode

To know if a DOM element is under the selection or not, you can use the method like this:

const foo = document.querySelector('#foo')
getSelection().containsNode(foo, true)

OR if you want to check which elements are currently under selection, you can instead try this:

function getElementsInSelection() {
    let selection = window.getSelection();
    if (!selection.rangeCount) return [];
    let elements = [];
    document.querySelectorAll('*').forEach(node => {
        if (selection.containsNode(node, true)) elements.push(node);
    });
    return elements;
}
发布评论

评论列表(0)

  1. 暂无评论