<h3>Something here</h3>
<p id="copythis">Copy this code</p>
<h3>Something here</h3>
<p id="copythisone">Copy this other text</p>
<h3>Something here</h3>
<p id="copythisone">Copy this other text</p>
<script type="text/javascript">
$(document).ready(function(){
$('#copythis').click(function(){
var text = $("#copythis").get(0)
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
})
});
</script>
I have different texts to copy (not all at once).
this code works for one text only. How do I work for more than one?
I just changed this part and it worked:
```var text = $(this).get(0)```
Thaks to @wahwahwah
$('#copythis').on("click", function(){
console.log($(this).text() + ": you clicked on '#copythis' ");
});
$('.copy').on("click", function(){
console.log($(this).text() + ": you clicked on a element with the class 'copy'");
});
$('p').on("click", function(){
console.log($(this).text() + ": you clicked on a <p> element'");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Something here</h3>
<p id="copythis" class="copy">Copy this code</p>
<h3>Something here</h3>
<p id="copythisone" class="copy">Copy this other text</p>
<h3>Something here</h3>
<p id="copythisone" class="copy">Copy this other text</p>
With JQuery, you can use .text() to get the contents of a p element. You could also change your selector to just grab the contents of all 'p' elements. The ID selector .(#copythis) will grab the element related to only that ID. The class selector (.copy) will attach to all elements with the class "copy."
This will help you isolate what's being clicked on. What you want to do with it - copy the contents to clipboard - might change the logic a bit depending on if you have control over the HTML source, and how your deciding what gets copied and doesn't.
I don't know what you are planning to do do, but basically this line
var text = $("#copythis").get(0);
is where the p-node will be selected from your dom an afterwards the content of this p-tag will be copied.
change it to
var text = $("#copythisone").get(0);
to copy the content of the 2nd p -tag
You could change the id of your third p-tag to sth. like copythisonetoo
var text = $("#copythisonetoo").get(0);
to get the content of the 3rd p tag.
But per definition an id should be unique in your document. Refer to this link: https://www.w3schools.com/html/html_id.asp#:~:text=The%20id%20attribute%20specifies%20a,element%20with%20the%20specific%20id.
You could create a method with a parameter for the text to copy or an id.
With some additional info and your certain usecase we could probably help you most.