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.