简体   繁体   中英

Programmatically selecting text in JavaScript

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 (ie it contains the following two spans):

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

No jquery, please.

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> 

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