2
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?

Community
  • 1
  • 1
db2791
  • 1,040
  • 6
  • 17
  • 30

1 Answers1

1

Since what you are selecting is not a valid HTML, for example has missing opening and closing tags, so the code you listed in your question wont work as expected, In your case you need to use a Text Selection function, something like that: https://stackoverflow.com/a/169873/200713

function getSelectedText() {
  var txt = '';

  if (window.getSelection) {
    txt = window.getSelection();
  }
  else if (document.getSelection) {
    txt = document.getSelection();
  }
  else if (document.selection) {
    txt = document.selection.createRange().text;
  }
  else return; 

  return txt;
}
Community
  • 1
  • 1
Neri Barakat
  • 1,555
  • 20
  • 25