I know that there is a similar question but when I try it, it doesn't work. I figured out that it's because I've changed the position of the button above the div I want to copy, but I don't know how to fix it :/ I must say I haven't understood the JS :/
function copy() {
var target = document.getElementById('mydiv');
var range, select;
if (document.createRange) {
range = document.createRange();
range.selectNode(target)
select = window.getSelection();
select.removeAllRanges();
select.addRange(range);
document.execCommand('copy');
select.removeAllRanges();
} else {
range = document.body.createTextRange();
range.moveToElementText(target);
range.select();
document.execCommand('copy');
}
}
#mydiv{
border: solid black 1px;
border-radius: 4x;
margin: 10px 0px;
}
<input onclick="copy()" type="button" value="Copy" />
<p></p>
<div>Insert text below</div>
<div id="mydiv" contenteditable="true"></div>
Use range.selectNodeContents(target) instead of range.selectNode(target) to avoid copying the outerHTML as well
function copy() {
var target = document.getElementById('mydiv');
var range, select;
if (document.createRange) {
range = document.createRange();
range.selectNodeContents(target)
select = window.getSelection();
select.removeAllRanges();
select.addRange(range);
document.execCommand('copy');
select.removeAllRanges();
} else {
range = document.body.createTextRange();
range.moveToElementText(target);
range.select();
document.execCommand('copy');
}
}
#mydiv{
border: solid black 1px;
border-radius: 4x;
margin: 10px 0px;
}
<input onclick="copy()" type="button" value="Copy" />
<p></p>
<div>Insert text below</div>
<div id="mydiv" contenteditable="true"></div>