HTML return from user selected text
I have the following very simple html page:
<html> <head> <script type="text/javascript"> function alertSelection() { var selection = window.getSelection(); var txt = selection.toString(); alert(txt); } </script> </head> <body> This is <span style="background-color:black;color:white">the</span> text. <div style="background-color:green;width:30px;height:30px;margin:30px" onmouseover="alertSelection()"> </body> </html> When I select the entire first row and point a square at a square, I get a warning that says "This is text."
How can I fix this so that the span tag or any other selected HTML is not removed from the warning message?
edit: I am looking specifically for how to get full HTML from window.getSelection() . The warning dialog was exactly how I tried to check the code. My only concern is working in Safari.
Here is the function that will receive the HTML code 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()); Use Rangy: https://github.com/timdown/rangy
Cross-browser library and selection library.
Check out the demo here: http://rangy.googlecode.com/svn/trunk/demos/index.html
Alerts do not display HTML, just text. You cannot force HTML to appear in the warning window.
What you can do is use the JS alert box replacement instead of alert , like jQuery Dialog , jQuery plugin, or something else completely.