1

I know that you can call a certain form element to focus using JavaScript, which for some reason makes me feel like it shouldn't be hard to achieve my task. As part of a function, I want to leave the user with the contents of a particular div selected (so that they can easily copy it with control-c).

In case it matters, the div contains content besides pure text (i.e. it contains the following two spans):

<span style="font-weight:bold; text-transform: capitalize;" id="part1"></span><span id="part2"></span>

No jquery, please.

Cœur
  • 37,241
  • 25
  • 195
  • 267
COMisHARD
  • 867
  • 3
  • 13
  • 36
  • You could probably start by looking here. http://stackoverflow.com/questions/985272/selecting-text-in-an-element-akin-to-highlighting-with-your-mouse – thanksd Nov 06 '15 at 03:32
  • Possible duplicate of [Selecting text in an element (akin to highlighting with your mouse)](https://stackoverflow.com/questions/985272/selecting-text-in-an-element-akin-to-highlighting-with-your-mouse) – Webdeveloper_Jelle Jan 21 '19 at 07:58

1 Answers1

0

How about :

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
 <script>
 function selectText(){
  document.getElementById('txt1').value = document.getElementById('xpto').innerHTML;
  document.getElementById('txt1').focus();
             document.getElementById('txt1').select();
 }
 </script>
</head>
<body>
 <div id="xpto"><span style="font-weight:bold; text-transform: capitalize;" id="part1"></span><span id="part2"></span></div>
 <form>
  <textarea id="txt1" name="txt1"></textarea>
  <button onclick="selectText()" type="button">Select text to copy</button>
 </form>
</body>
</html>
Telmo Dias
  • 3,938
  • 2
  • 36
  • 48