6

I am trying to identify whether a selected text (in Firefox) is bold or not? For e.g.:

<p>Some <b>text is typed</b> here</p>

<p>Some <span style="font-weight: bold">more text is typed</span> here</p>

The user can either select a part of bold text, or the full bold text. Here is what I am trying to do:

function isSelectedBold(){
    var r = window.getSelection().getRangeAt(0);
    // then what?
}

Could you please help me?

Thanks
Srikanth

Srikanth Vittal
  • 476
  • 7
  • 22

1 Answers1

16

If the selection is within an editable element or document, this is simple:

function selectionIsBold() {
    var isBold = false;
    if (document.queryCommandState) {
        isBold = document.queryCommandState("bold");
    }
    return isBold;
}

Otherwise, it's a little trickier: in non-IE browsers, you'll have to temporarily make the document editable:

function selectionIsBold() {
    var range, isBold = false;
    if (window.getSelection) {
        var sel = window.getSelection();
        if (sel && sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            document.designMode = "on";
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
    if (document.queryCommandState) {
        isBold = document.queryCommandState("bold");
    }
    if (document.designMode == "on") {
        document.designMode = "off";
    }
    return isBold;
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Thank you so much. I will settle with this workaround for now. – Srikanth Vittal Aug 16 '10 at 15:06
  • This feature (`queryCommandState `) is now deprecated... :/ – Cyril N. Jul 03 '20 at 21:15
  • @CyrilN. If there's an alternative API that deals with a range (which is what you get from a selection), I'm not aware of it. I'm not delighted about APIs being removed from the web platform without replacement. In this case, you could do a manual traversal of the elements that are selected or partially selected by the selection ([here's a starting point](https://stackoverflow.com/a/7931003/96100), you'll need to filter out non-element nodes though) and use [`getComputedStyle()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle) to check each. – Tim Down Jul 06 '20 at 16:46
  • @TimDown Yes, I tried to do that, and finally went back to use queryCommandState with the assumption that at some point, an awesome dev will build a compatible API :D – Cyril N. Jul 07 '20 at 11:55