0

Below is what I am trying to do:

I found the below js function which displays the selected text in a textarea

function getSelected() {
  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;
  document.selectedtext.value =  txt;
}

<textarea name="selectedtext" rows="5" cols="20"></textarea>

But what I am trying to achieve is to get the HTML elements as well while getting copied. For example:

<div>some text is entered here</div>
<div>line2</div>

With above JS, content in textarea is:

some text is entered here
line2

What I am expecting is:

<div>some text is entered here</div>
<div>line2</div>

1 Answer 1

0

This is a somewhat complex question than it appears at first blush because there are all sorts of edge cases where a user selects some content in a container but not all of its content. In this case should it intelligently wrap the fragment with the parent div? Are you trying to carry over styles or more than one level of DOM hierarchy? I would highly recommend the Rangy Library, which deals with many of these pitfalls. In particular I would check out the toHtml() method from the selection object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.