How can I get the DOM element which contains the current selection?

dom, html, javascript, selection

Solution

In IE, use document.selection.createRange().parentElement() and in real browsers use window.getSelection().getRangeAt(0).startContainer.parentNode. Something like this:

function getSelectedNode()
{
    if (document.selection)
        return document.selection.createRange().parentElement();
    else
    {
        var selection = window.getSelection();
        if (selection.rangeCount > 0)
            return selection.getRangeAt(0).startContainer.parentNode;
    }
}

Problem

You can select a part of a web page with the mouse. I know that I can get the currently selected text but how can I get the DOM element which contains the start or end of the current selection?

Original source

Related problems