According to MDN Web Docs
The HTMLInputElement.select() method selects all the text in a element or in an element that includes a text field.
That means .select() does not work on the element other than input and textarea. In my case, I have some strings in code and pre that I would like user to click on copy button to copy the text inside but according to definition above that does not work.
$(document).ready(function() {
$('code, pre').append('<span class="command-copy" ><i class="fa fa-clipboard" aria-hidden="true"></i></span>');
$('code span.command-copy').click(function(e) {
text = $(this).parent().select(); //.text();
copiedText = $.trim(text);
document.execCommand("copy");
});
$('pre span.command-copy').click(function(e) {
text = $(this).parent().parent().select(); //.text();
copiedText = $.trim(text);
document.execCommand("copy");
});
})
code,
pre {
position: relative;
}
code,
pre {
display: block;
padding: 20px;
background: #f2f2f2;
color: #555755;
}
span.command-copy {
position: absolute;
top: 10px;
right: 10px;
opacity: .6;
font-size: 20px;
color: #555755;
}
span.command-copy:hover {
cursor: pointer;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<h4>
<b>Steps to install pytest</b>
</h4>
<p>
<b>Step 1: </b>Open the terminal and type in this command:
</p>
<code class="command-copy">
pip install pytest
</code>
<p>Or you can upgrade your existing:
<p>
<pre><span></span><span class="nv">pip</span> install --upgrade pytest
<span class="command-copy"><i class="fa fa-clipboard" aria-hidden="true"></i></span></pre>
Is any way I can work around this? Thanks