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 line and mouseover the square, I get an alert with "This is the text.".
How would I fix this so the the span tag or any other selected HTML isn't stripped out of the alert message?
edit: I'm looking specifically for how to get the full HTML from window.getSelection()
. The alert dialog was just how I was attempting to validate the code. I'm only concerned about this working in Safari.
Here's a function that will get you HTML corresponding to the current selection in all major browsers:
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.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