简体   繁体   中英

selecting text along with element using jquery

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM