JSFiddle - React, Tailwind, and code Playground

by Graham Fairweather

HTML

<div id="start">
    <p>nicks test</p>
    <p>more bring text</p>
    <h2>This is my headline</h2>
</div>
<button id="get">Get Selected</button>

JavaScript

function checkNodes(element, text) {
    if (typeof text !== "string" && text === "") {
        return;
    }

    var content;
    
    for (var child = element.firstChild; child !== null; child = child.nextSibling) {
        if (child.nodeType === 3) {
            child.parentElement.style.background = "white";
            content = child.textContent;
    
            if (content.replace(/\s/g, "") !== "" && (text.length >= content.length) && text.indexOf(content) !== -1) {
                child.parentElement.style.background = "red";
                console.log("this element matches: ", content, child.parentElement);
            }
        } else if (child.nodeType === 1) {
            checkNodes(child, text);
        }
    }
}

function getText() {
    var selectedText

    if (typeof window.getSelection === "function") {
        selectedText = window.getSelection();
    } else if (typeof document.getSelection === "function") {
        selectedText = document.getSelection();
    } else if (document.selection && typeof document.selection.createRange() === "function") {
        selectedText = document.selection.createRange().text;
    } else {
        selectedText = "";
        alert("No method to get selected text");
    }

    if (!selectedText || selectedText === "") {
        if (document.activeElement.selectionStart) {
            selectedText = document.activeElement.value.substring(
            document.activeElement.selectionStart.document.activeElement.selectionEnd);
        }
    }

    checkNodes(document.getElementById("start"), selectedText.toString());
}

document.getElementById("get").addEventListener("click", getText, false);