Search code examples
javascripthtmlwysiwygselection

Javascript: get html around user selection?


It is possible to get whatever the user has selected with the mouse using Javascript, like this: http://www.motyar.info/2010/02/get-user-selected-text-with-jquery-and.html

My issue is that I do not just need this text, but I also need:

  1. to get the html surrounding this text (eg. if the user selects "hello" and this hello is in the source produced as: "<div><span>hello</span></div>" that is what it should return).

  2. to do the same for graphics

Can anyone guide me through this process, or are there alternatives if this is not possible?


Solution

  • This will do it in all major browsers. There are separate branches for IE and more standards-compliant browsers. In IE, it's slightly easier because the proprietary TextRange object created from the selection has a handy htmlText property. In other browsers, you have to use the cloneContents() method of DOM Range to create a DocumentFragment containing a copy of the selected content and obtain the HTML from this by appending the fragment to an element and returning the element's innerHTML property.

    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;
            }
        }
        return html;
    }
    
    alert(getSelectionHtml());