-2

I am displaying an address as below. I would like the user to be able to click on any part of the address and have the inner html of the two nested divs be highlighted, so they can then copy to clipboard. This would be the same result as simply holding down left mouse and dragging the cursor from the beginning of the address to the end.

<div id="my-id">
  <div >1 Main St</div>
  <div >Anytown, KY</div>
</div>

Looking for a JavaScript solution.

thanks!

dt1000
  • 3,684
  • 6
  • 43
  • 65
  • 1
    Possible duplicate of [Selecting text in an element (akin to highlighting with your mouse)](http://stackoverflow.com/questions/985272/selecting-text-in-an-element-akin-to-highlighting-with-your-mouse) – Paul Abbott May 19 '16 at 17:42

1 Answers1

0

I would build off of this answer: https://stackoverflow.com/a/4183448/3362735 and add an onclick event or attach an event handler to the element.

function selectElement(el) {
  if (window.getSelection && document.createRange) {
    var sel = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(el);
    sel.removeAllRanges();
    sel.addRange(range);
  } else if (document.selection && document.body.createTextRange) {
    var textRange = document.body.createTextRange();
    textRange.moveToElementText(el);
    textRange.select();
  }
}
<div id="my-id" onclick="selectElement(this)">
  <div>1 Main St</div>
  <div>Anytown, KY</div>
</div>
Community
  • 1
  • 1