I'm working on a javascript extension for IE and I'd like to capture the HTML of a page and add an anchor and highlighting around the current selection. I've gotten this mostly working several different ways, but each approach has problems. I'd like to leave the original page unmodified, which is harder than it seems. For example, I've tried getting a TextRange and calling pasteHTML as follows:
var rng = document.selection.createRange();
var h = rng.htmlText;
rng.pasteHTML("<span STYLE=\"background-color:yellow\">" + h + "</span>");
and other variations based on this approach. The problem with that is that the htmlText method doesn't return partial HTML, so if the selection includes a closing <p
> but not the start, it disappears and wrecks the formatting of the source page.
I've also looked at calling execCommand with the "BackColor" and "CreateBookmark" methods to change the formatting, but again I end up changing the original page, which I don't want to do.
Is there some way to get a copy of the page with the selection set and wrap the selection in a span without modifying the original page and without losing any HTML tags?
EDIT: My end goal is to copy the modified HTML to the clipboard, so the source page is unmodified but the copied HTML text has the anchor and highlighting.