-1

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.

Grandtour
  • 1,127
  • 1
  • 11
  • 28

2 Answers2

4

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>
Nam V. Do
  • 630
  • 6
  • 27
0

You are looking to surround the highlighted text into a new node that you add new style to. Check out this answer How To Wrap / Surround Highlighted Text With An Element

Pablo
  • 5,897
  • 7
  • 34
  • 51