Range.surroundContents - didn't occur to me
Nice job.
Perhaps it may be slightly better to run object detection on the specific functions we're going to use though? Also if there is more than one range selected by the user, the code will only return the first range. Also changed "p" to "span" so it wouldn't interfere with the page layout.
Code:
function getSelectionHTML()
{
if (window.getSelection)
{
var sel = window.getSelection();
var html = "";
for (var i=0;i<sel.rangeCount;i++)
{
/*Author: rnd_me*/
var nNd = document.createElement("span");
var w = sel.getRangeAt(i);
w.surroundContents(nNd);
html += nNd.innerHTML;
}
return html;
}
else if (document.selection && document.selection.createRange) return (document.selection.createRange()).htmlText;
return null;
}
This still adds a span every time you run it. Since the OP wanted to return the html of the selected text, it seems like it might be an issue adding html to the html in question... Maybe there's an easy way to remove the spans once we're done with them? .outerHTML = .innerHTML would do the trick if all browsers supported outerHTML (most do not

).