Return HTML from a user-selected text
Use Rangy: https://github.com/timdown/rangy
Cross-browser range and selection library.
Check out the demos here: http://rangy.googlecode.com/svn/trunk/demos/index.html
Here's a function that will get you HTML corresponding to the current selection in all major browsers:
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());
Alert boxes do not display HTML, just plain text. You can't get the HTML to show in an alert box.
What you can do is use some JS alert box replacement instead of alert
, such as jQuery Dialog, a jQuery plugin, or something else entirely.