JSFiddle - React, Tailwind, and code Playground

by jfriend00

HTML

<div id="1">
    <div id="a">Here</div>
    <div id="b">is</div>
    <div id="c">some <i id="d">italics</i></div>
    <div id="e">text</div>
</div>

<button onclick="test()">Test</button><br><br>
Common Parent id = <span id="result"></span>

JavaScript

function findCommonParentElement(startNode, endNode) {
    
    // see if node has a particular parent 
    // by walking up the parent chain and comparing parents
    function hasParent(node, parent) {
        while (node && node !== parent && node !== document.body) {
            node = node.parentNode;
        }
        return node === parent;
    }
    
    // for text nodes, get the containing element
    // for elements, just return what was passed in
    function getElement(node) {
        while (node && node.nodeType !== 1) {
            node = node.parentNode;
        }
        return node;
    }

    // go up the parent chain of endNode looking for a node 
    // that startNode has as a parent    
    while (endNode && !hasParent(startNode, endNode)) {
        endNode = endNode.parentNode;
    }
    // return the containing element - so it won't return a textnode
    return getElement(endNode);
}

function test() {
    var sel = window.getSelection();
    var commonParent = findCommonParentElement(sel.anchorNode, sel.focusNode);
    document.getElementById("result").innerHTML = commonParent.id;
}