javascripthtmlfont-style

How to change font style of window.getSelection()


I want to know how can I change the font style of the selected text, using window.getSelection(), after clicking in a button.

For example, supose that we have the following phrase:

Hello world!

If I just select the string ell from it and after that, click in a button, it will return (in this case, for example, bold type):

Hello world!

So, how could I do that? My main problem is: what variable type should I convert the window.getSelection() to change the font style, because it returns a object, and if I did .toString(), it won't help very much.


Solution

  • function surroundSelection() {
            var span = document.createElement("span");
            span.style.fontWeight = "bold";
            span.style.color = "black";
    
            if (window.getSelection) {
                var sel = window.getSelection();
                if (sel.rangeCount) {
                    var range = sel.getRangeAt(0).cloneRange();
                    range.surroundContents(span);
                    sel.removeAllRanges();
                    sel.addRange(range);
                }
            }
        }
    <input type="button" onclick="surroundSelection()" value="Surround">
        <div contenteditable="true">Hello World</div>