JSFiddle - React, Tailwind, and code Playground

by timdown

HTML

<input type="button" onmousedown="alert(getSelectionRangeText())" value="get selected text">
<div>
    <img src="someSrc.jpg" alt="image_alt" /> <script>var foo = "bar";</script>My text here ...
</div>

JavaScript

function getSelectionRangeText() {
    var selText = "", selTextParts = [];

    function getNodeText(node) {
        if (node.nodeType == 3) {
            selTextParts.push(node.data);
        } else if (node.hasChildNodes() && !(node.nodeType == 1 && /^(script|style)$/i.test(node.tagName))) {
            for (var child = node.firstChild; !!child; child = child.nextSibling) {
                getNodeText(child);
            }
        }
    }

    if (window.getSelection) {
        var sel = window.getSelection(), rangeCount = sel.rangeCount;
        if (rangeCount) {
            for (var i = 0; i < rangeCount; ++i) {
                getNodeText(sel.getRangeAt(i).cloneContents());
            }
            selText = selTextParts.join("");
        }
    } else if (document.selection && document.selection.type == "Text") {
        selText = document.selection.createRange().text;
    }
    return selText;
}