0

I want to select the HTML of whatever the user selects in a contenteditable div. I found some code to retrieve the HTML of the selection, but it's not limited to just the div.

What I want to do is copy the selected HTML, wrap tags around it, and then replace the selection with it. So, 'test' would become 'test' for instance.

<div contenteditable="true" class="body" id="bodydiv"></div>

function getSelectionHtml() {
    var html = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
}
jcvamp
  • 25
  • 8
  • thsi would be helpful https://stackoverflow.com/a/3997896/2630817 – Just code Dec 21 '18 at 05:50
  • Thanks for the response. I've seen that. The only issue is that it applies to any text you select including things outside of the div. – jcvamp Dec 21 '18 at 05:54

1 Answers1

0

HI for getting content(text) inside a selected div I have create a little code you can check it out if it works for you :

$(document).ready(function(){
         $(document).bind('mouseup', function(){
         var content =  getSelected();
            content = "<b>"+content+"</b>";
            $('#selected').html(content);
        });
});

    function getSelected(){
        var t;
        if(window.getSelection){
           t = window.getSelection();
           var start = t.focusOffset;
           var end = t.baseOffset;
           t = t.anchorNode.data;
           t = t.slice(start, end);
        }  else if (document.selection) {
             t = document.selection.createRange().text;
        }
        return t;
    }

And

<div id="selected"></div>

Hope this helps.

kshitij
  • 642
  • 9
  • 17