JSFiddle - React, Tailwind, and code Playground

by timdown

HTML

<script src="http://rangy.googlecode.com/svn/trunk/currentrelease/rangy-core.js"></script>
<div contenteditable="true" onmouseup="splitParaAtCaret()">
    <p>This is <a href="#">a test</a>, you like?</p>
</div>

JavaScript

function splitParaAtCaret() {
    var sel = rangy.getSelection();
    if (sel.rangeCount > 0) {
        // Create a copy of the selection range to work with
        var range = sel.getRangeAt(0).cloneRange();
    
        // Get the containing paragraph
        var p = range.commonAncestorContainer;
        while (p && (p.nodeType != 1 || p.tagName != "P") ) {
            p = p.parentNode;
        }
     
        if (p) {
            // Place the end of the range after the paragraph
            range.setEndAfter(p);
    
            // Extract the contents of the paragraph after the caret into a fragment
            var contentAfterRangeStart = range.extractContents();
    
            // Collapse the range immediately after the paragraph
            range.collapseAfter(p);
            
            // Insert the content
            range.insertNode(contentAfterRangeStart);
    
            // Move the caret to the insertion point
            range.collapseAfter(p);
            sel.setSingleRange(range);
        }
    }
}