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;
}
I am using the code above that's provided here: How to get selected html text with javascript?.
However, there are so inconsistencies with the actual html and the html that's returned by the function. For example, given the following html:
<div>
<p><b>The quick brown fox jumps over the lazy <a href="www.google.com">dog</a></b></p>
<img src="http://www.fakingnews.firstpost.com/wp-content/uploads/2015/12/kim-jaya.jpg" alt="Smiley face" height="42" width="42">
<hr>
<p>The quick brown fox jumps over the lazy <a href="http://www.google.com">dog</a></p>
<li>
<ul>1</ul>
<ul>2</ul>
<ul>3</ul>
<ul>4</ul>
<ul>5</ul>
</li>
</div>
<br />
<input id="showSelected" type="button" value="showSelected" />
If I was to select
x jumps over the lazy <a href="http://www.google.com">dog</a></p>
<li>
<ul>1</ul>
<ul>2</ul>
<ul>3</ul>
The function actually returns
<div><p>x jumps over the lazy <a href="http://www.google.com">dog</a></p>
<li>
<ul>1</ul>
<ul>2</ul>
<ul>3</ul>
<ul>4</ul>
<ul>5</ul>
</li>
</div>
I've noticed that the extra tags in the front appear when I also select a list, but I'm sure there are other instances of inconsistency as well. Is there anything I can do to get an exact HTML copy?