JSFiddle - React, Tailwind, and code Playground

HTML

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<div id="main-input" contenteditable="true">Hello world!</div>
<button type="button" class="icon-bold">Bold</button>

JavaScript

var lastCaretIndex = null;
    document.addEventListener('selectionchange', function(event) {
        var taget = event.target;
        if (taget.activeElement.id == 'main-input') {
            lastCaretIndex = getSelectionRange();

            console.log(typeof lastCaretIndex);
            console.log(lastCaretIndex);
        }
    });

    function afterFocus() {
        var s = null;
        if (window.getSelection) {
            s = window.getSelection();
        } else {
            s = document.getSelection();
        }

        if (lastCaretIndex == null) {
            lastCaretIndex = document.createRange();
        } else if (s.rangeCount > 0) {
            s.removeAllRanges();
            s.addRange(lastCaretIndex);
        }
    }

    function getSelectionRange() {
        var sel;
        if (window.getSelection) {
            sel = window.getSelection();
            if (sel.rangeCount) {
                return sel.getRangeAt(0);
            }
        } else if (document.selection) {
            return document.createRange();
        }

        return null;
    }

    $(document).on('click', '.icon-bold', function () {
        document.getElementById('main-input').focus();
        afterFocus();
        document.execCommand('bold');
        handleButtonActiveState($(this));
    });