开发者

Determine HTML Node name given a javascript selection object

开发者 https://www.devze.com 2023-03-26 00:50 出处:网络
How can I determine the node (what tag this innerHTML is associated with) that is associated with a given ja开发者_StackOverflow社区vascript selection object?I am using window.getSelection() and would

How can I determine the node (what tag this innerHTML is associated with) that is associated with a given ja开发者_StackOverflow社区vascript selection object? I am using window.getSelection() and would like to know in which div/span class the selection is in.

Thank you!


If you want the deepest element that contains the whole of the selection, the easiest way is to obtain a Range object from the selection and use its commonAncestorContainer property.

jsFiddle: http://jsfiddle.net/5LvEG/1/

Code:

function getSelectionContainerElementId() {
    var sel = window.getSelection();
    if (sel.rangeCount > 0) {
        var range = sel.getRangeAt(0);
        var container = range.commonAncestorContainer;

        // container could be a text node, so use its parent if so
        if (container.nodeType == 3) {
            container = container.parentNode;
        }
        return container.id;
    }
    return null;
}

alert(getSelectionContainerElementId());
0

精彩评论

暂无评论...
验证码 换一张
取 消