JSFiddle - React, Tailwind, and code Playground

by Retsam19

HTML

This is some text <span class="target">This is the target text</span>  More text
<br><br>
<div id="indicator"></div>

CSS

.target {
    color: red
}

.full {
    color: green;
}

.partial {
    color: orange;
}

.none {
    color: red;
}
}

JavaScript

var indicator = document.getElementById("indicator");

function nodeInsideTarget(node) {
    return node.parentElement.classList.contains("target");
}

function checkSelection() {
    var sel = document.getSelection();
    if(!sel || !sel.anchorNode || !sel.focusNode) return;
    var startsInTarget = nodeInsideTarget(sel.anchorNode);
    var endsInTarget = nodeInsideTarget(sel.focusNode);
    
    if(startsInTarget && endsInTarget) {
        indicator.className = "full";
        indicator.innerHTML = "Selection starts and ends inside target";
    } else if(startsInTarget || endsInTarget) {
        indicator.className = "partial";
        indicator.innerHTML = "Selection is partially in target";
    } else {
        indicator.className = "none";
        indicator.innerHTML = "Selection is not in target";   
    }
        
}

window.setInterval(checkSelection, 1000);