Identify whether the selected text in a web page is bold nor not
Asked Answered
D

1

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

Delly answered 4/8, 2010 at 10:30 Comment(1)
Is this in an editable element (or document)?Elmaleh
E
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;
}
Elmaleh answered 4/8, 2010 at 11:34 Comment(4)
Thank you so much. I will settle with this workaround for now.Delly
This feature (queryCommandState ) is now deprecated... :/Lung
@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, you'll need to filter out non-element nodes though) and use getComputedStyle() to check each.Elmaleh
@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 :DLung

© 2022 - 2024 — McMap. All rights reserved.