JSFiddle - React, Tailwind, and code Playground

by Joel Peterson

HTML

<div>This is a paragraph</div>
<div>
    <em id="ignore">test</em>This is a second paragraph <strong>with</strong> fancy <p>content</p>
</div>
<ul id="output">
</ul>

JavaScript

document.addEventListener('mouseup', function() {
    var selection = window.getSelection();
    if (!selection.isCollapsed) {
        // we have a non-zero length selection
        var startNode = selection.anchorNode;
        var startOffset = selection.anchorOffset;
        if (startNode instanceof Element) {
            // if it is an element then the offset is the child node index
            startNode = startNode.childNodes[startOffset];
            startOffset = 0;
        }
        var endNode = selection.focusNode;
        var endOffset = selection.focusOffset;
        if (endNode instanceof Element) {
            // if it is an element then the offset is the child node index
            endNode = endNode.childNodes[endOffset];
            endOffset = 0;
        }
        //console.log(startNode, startOffset, endNode, endOffset);
        
        var range = selection.getRangeAt(0);
        var selectedText = range.toString();
        var selectedFragment = range.cloneContents();
        //console.log(selectedText);
        //console.log(selectedFragment);
        var clippedText = document.createElement('li');
        clippedText.appendChild(selectedFragment);
        document.getElementById('output').appendChild(clippedText);
        
        var root = range.commonAncestorContainer;
        
        //now let's split the text
        if (endNode instanceof Text) {
        	endNode.splitText(endOffset);
        }
        if (startNode instanceof Text) {
        	startNode.splitText(startOffset);
            startNode = startNode.nextSibling;
        }
        
        // filter out the element with id=ignore
        function filterFunction(node) { 
            if (node.id === 'ignore') {
            	return NodeFilter.FILTER_REJECT;
            }
            return NodeFilter.FILTER_ACCEPT;
        }
        
        var nodeTypes = NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT;
        
        var walker = document.createTreeWalker(root, nodeTypes, {...