So I have nested div
tags in the HTML file. I was trying to copy certain texts from each div
tag. After searching for several hours finally I found the solution which worked. The solution below:
<html>
<body>
<div id="a" onclick="copyDivToClipboard()"> Click to copy </div>
<script>
function copyDivToClipboard() {
var range = document.createRange();
range.selectNode(document.getElementById("a"));
window.getSelection().removeAllRanges(); // clear current selection
window.getSelection().addRange(range); // to select text
document.execCommand("copy");
window.getSelection().removeAllRanges();// to deselect
}
</script>
</body>
</html>
But since it was using id
it was only working for first div
. Then I changed id
to class
but then the solution found before was not working. My HTML file below:
<div>
<div onclick="copyTextToClipboard()">
<span>My favorite actor is <span class="text_to_copy">Robert Downey, Jr.</span></span>
</div>
<div onclick="copyTextToClipboard()">
<span>My favorite actor is <span class="text_to_copy">Tom Cruise</span></span>
</div>
<div onclick="copyTextToClipboard()">
<span>My favorite actor is <span class="text_to_copy">Hugh Jackman</span></span>
</div>
<div onclick="copyTextToClipboard()">
<span>My favorite actor is <span class="text_to_copy">Ryan Gosling</span></span>
</div>
</div>
After commenting on the solution I found, the he suggested me to check out Range.setStart()
and Range.setEnd()
. But I just can not figure out how to apply those since I am relatively new to Javascript
.
Also those several span
tags were used for different classes for styling.