Most of the proposed answers create an extra temporary hidden input element(s). Because most browsers nowadays support div content edit, I propose a solution that does not create hidden element(s), preserve text formatting and use pure JavaScript or jQuery library.
Here is a minimalist skeleton implementation using the fewest lines of codes I could think of:
//Pure javascript implementation:_x000D_
document.getElementById("copyUsingPureJS").addEventListener("click", function() {_x000D_
copyUsingPureJS(document.getElementById("copyTarget"));_x000D_
alert("Text Copied to Clipboard Using Pure Javascript");_x000D_
});_x000D_
_x000D_
function copyUsingPureJS(element_id) {_x000D_
element_id.setAttribute("contentEditable", true);_x000D_
element_id.setAttribute("onfocus", "document.execCommand('selectAll',false,null)");_x000D_
element_id.focus();_x000D_
document.execCommand("copy");_x000D_
element_id.removeAttribute("contentEditable");_x000D_
_x000D_
}_x000D_
_x000D_
//Jquery:_x000D_
$(document).ready(function() {_x000D_
$("#copyUsingJquery").click(function() {_x000D_
copyUsingJquery("#copyTarget");_x000D_
});_x000D_
_x000D_
_x000D_
function copyUsingJquery(element_id) {_x000D_
$(element_id).attr("contenteditable", true)_x000D_
.select()_x000D_
.on("focus", function() {_x000D_
document.execCommand('selectAll', false, null)_x000D_
})_x000D_
.focus()_x000D_
document.execCommand("Copy");_x000D_
$(element_id).removeAttr("contenteditable");_x000D_
alert("Text Copied to Clipboard Using jQuery");_x000D_
}_x000D_
});
_x000D_
#copyTarget {_x000D_
width: 400px;_x000D_
height: 400px;_x000D_
border: 1px groove gray;_x000D_
color: navy;_x000D_
text-align: center;_x000D_
box-shadow: 0 4px 8px 0 gray;_x000D_
}_x000D_
_x000D_
#copyTarget h1 {_x000D_
color: blue;_x000D_
}_x000D_
_x000D_
#copyTarget h2 {_x000D_
color: red;_x000D_
}_x000D_
_x000D_
#copyTarget h3 {_x000D_
color: green;_x000D_
}_x000D_
_x000D_
#copyTarget h4 {_x000D_
color: cyan;_x000D_
}_x000D_
_x000D_
#copyTarget h5 {_x000D_
color: brown;_x000D_
}_x000D_
_x000D_
#copyTarget h6 {_x000D_
color: teal;_x000D_
}_x000D_
_x000D_
#pasteTarget {_x000D_
width: 400px;_x000D_
height: 400px;_x000D_
border: 1px inset skyblue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="copyTarget">_x000D_
<h1>Heading 1</h1>_x000D_
<h2>Heading 2</h2>_x000D_
<h3>Heading 3</h3>_x000D_
<h4>Heading 4</h4>_x000D_
<h5>Heading 5</h5>_x000D_
<h6>Heading 6</h6>_x000D_
<strong>Preserve <em>formatting</em></strong>_x000D_
<br/>_x000D_
</div>_x000D_
_x000D_
<button id="copyUsingPureJS">Copy Using Pure JavaScript</button>_x000D_
<button id="copyUsingJquery">Copy Using jQuery</button>_x000D_
<br><br> Paste Here to See Result_x000D_
<div id="pasteTarget" contenteditable="true"></div>
_x000D_