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.getSelectio开发者_JAVA技巧n() would get us the currently selected text. But how can we determine which DOM elements are contained in this text selection?
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 common 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 compareEndPoints
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 comparing, which isn't fun at all.
精彩评论