JSFiddle - React, Tailwind, and code Playground

by sirfizx

HTML

<input type="button" onmousedown="reportColourAndFontSize(); return false" value="Get colour and font size">

<div contenteditable="true"><span style="font-size: 2em">Large text</span> and <span style="color: red">red text</span></div>

JavaScript

function getComputedStyleProperty(el, propName) {
    if (window.getComputedStyle) {
        return window.getComputedStyle(el, null)[propName];
    } else if (el.currentStyle) {
        return el.currentStyle[propName];
    }
}

function reportColourAndFontSize() {
    var containerEl, sel;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            containerEl = sel.getRangeAt(0).commonAncestorContainer;
            // Make sure we have an element rather than a text node
            if (containerEl.nodeType == 3) {
                containerEl = containerEl.parentNode;
            }
        }
    } else if ( (sel = document.selection) && sel.type != "Control") {
        containerEl = sel.createRange().parentElement();
    }
    
    if (containerEl) {
        var fontSize = getComputedStyleProperty(containerEl, "fontSize");
        var colour = getComputedStyleProperty(containerEl, "color");
        alert("Colour: " + colour + ", font size: " + fontSize);
    }
}