javascript,js,get,nodesselectionselected

Kubilay 4/12/2017 0

Get selected nodes from selection by javascript

JavaScript
 function getNodesInSelection(selection) {

    // MOD #1
    // When the startContainer/endContainer is an element, its
    // startOffset/endOffset basically points to the nth child node
    // where the range starts/ends.
    var nodes = [];

    if (selection.toString() != "" && selection.rangeCount > 0) {
        var range = selection.getRangeAt(0);
        var startElm = range.startContainer.childNodes[range.startOffset] || range.startContainer;
        var endElm = range.endContainer.childNodes[range.endOffset] || range.endContainer;
        var commonAncestor = $(".article-container")[0];

        var node;
        var start;
        var end;

        // walk parent nodes from start to common ancestor
        for (node = startElm; node; node = node.parentNode) {
            if (node == commonAncestor)
                break;
            if (node.parentNode == commonAncestor)
                start = node;
        }

        for (node = endElm; node; node = node.parentNode) {
            if (node == commonAncestor)
                break;
            if (node.parentNode == commonAncestor)
                end = node;
        }

        // walk children and siblings from start until end is found
        for (node = start; node; node = node.nextSibling) {

            if (!$(node.parentNode).closest(commonAncestor)[0]) break;

//ignore text nodes and empty nodes if (node.nodeType != 3 && $(node).text().trim().length > 0) { nodes.push(node); } if (node == end) break; } } return nodes; }

Report Bug

Please Login to Report Bug

Reported Bugs

Comments

Please Login to Comment

Comments