JSFiddle - React, Tailwind, and code Playground

HTML

<section class="detailBox" id="detailBox" contenteditable="true">
     <h3 class="detailBoxHeading">Highlight a part of the text below, then press the button</h3>

    <p class="detailBoxParagraph" id="detailBoxParagraph">'Lorem ipsum dolor sit amet, consetetur sadipscing elitr.</p>
</section>
<input type="button" class="toolboxElement" unselectable="on" value="Set to bold">

JavaScript

function getSelectionCharOffsetsWithin(element) {
    var start = 0,
        end = 0;
    var sel, range, priorRange;
    if (typeof window.getSelection != "undefined") {
        range = window.getSelection().getRangeAt(0);
        priorRange = range.cloneRange();
        priorRange.selectNodeContents(element);
        priorRange.setEnd(range.startContainer, range.startOffset);
        start = priorRange.toString().length;
        end = start + range.toString().length;
    } else if (typeof document.selection != "undefined" && (sel = document.selection).type != "Control") {
        range = sel.createRange();
        priorRange = document.body.createTextRange();
        priorRange.moveToElementText(element);
        priorRange.setEndPoint("EndToStart", range);
        start = priorRange.text.length;
        end = start + range.text.length;
    }
    return {
        start: start,
        end: end
    };
}

(function ($) {
    var methods = {

        setBold: function () {

            var mainDiv = document.getElementById("detailBoxParagraph");
            var sel = getSelectionCharOffsetsWithin(mainDiv);

            var substract = sel.end - sel.start;

            var text = $('.detailBox p').html();

            text = text.substr(0, sel.start) + "<b> " + text.substr(sel.start, substract) + "</b>" + text.substr(sel.start + substract); // Here is my failure i guess


            $('.detailBoxParagraph').html(text);

            // As the <b> tag is added to the html by the first time, the second call will not work since the positions do not match

        },

        init: function (options) {
        //...
        }
    };

    $.fn.editMe = function (method) {

        // Method calling logic
        if (methods[method]) { // if a method is passed as a parameter
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } 
    };
    
    //------------------------------
    
    $('.detailBox').editMe();
   ...