I need the text to be copied by clicking, but not highlighted. I can not understand what method is responsible for the selection. Googled that selectNodeContents() selects text, but this does not work. Maybe someone can tell?

 $(document).ready(function () { function selectText(elementId) { var doc = document, text = doc.getElementById(elementId), range, selection; if (doc.body.createTextRange) { range = document.body.createTextRange(); range.moveToElementText(text); range.select(); } else if (window.getSelection) { selection = window.getSelection(); range = document.createRange(); range.selectNodeContents(text); selection.removeAllRanges(); selection.addRange(range); } } $("#linkCopy").click(function() { selectText(this.id); document.execCommand("copy"); $('.link__url-icon').css("display", "block"); }); }); 
 .link__url { display: flex; } .link__url-icon { display: none; margin-left: 15px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="link__url" id="linkCopy">https://www.google.com.ua/?hl=ru<span class="link__url-icon"><img src="./images/copy.svg"></span></span> 

    1 answer 1

    The selection object is responsible for the selection , and the text is highlighted after you have added the range .

    To reset the selection, simply delete all the selected intervals after the document.execCommand("copy"); function executes document.execCommand("copy"); . To do this, you can return the selection object from the function and clear it immediately after the call, for example:

     $(document).ready(function() { function selectText(elementId) { var doc = document, text = doc.getElementById(elementId), range, selection; if (window.getSelection) { selection = window.getSelection(); range = document.createRange(); range.selectNodeContents(text); selection.removeAllRanges(); selection.addRange(range); return selection; } } $("#linkCopy").click(function() { var s = selectText(this.id); document.execCommand("copy"); s.removeAllRanges(); $('.link__url-icon').css("display", "block"); }); }); 
     .link__url { display: flex; } .link__url-icon { display: none; margin-left: 15px; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="link__url" id="linkCopy">https://www.googwwwle.com.ua/?hl=ru<span class="link__url-icon"><img src="./images/copy.svg"></span></span>