window.getSelection return html [duplicate]

霸气de小男生 提交于 2019-11-26 14:18:08

问题


function selected() {
   var selObj = window.getSelection();
}


This function returns selected text from a webpage. How do return the html of a selected area. Is this possible to do with an <img> and an <a> tag?


Here's the list of functions:
https://developer.mozilla.org/Special:Tags?tag=DOM&language=en


回答1:


The following will do this in all major browsers and is an exact duplicate of this answer:

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;
}


来源:https://stackoverflow.com/questions/5222814/window-getselection-return-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!