javascript – How to highlight div content and copy content to clipboard?

Question:

How to highlight the content of a div with jQuery on click?

And the second question: how to copy the contents to the clipboard?

Answer:

Code taken from here

function selectText(elementId) {
    var doc = document,
        text = doc.getElementById(elementId),
        range,
        selection;
        
    if (doc.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) {
        selection = window.getSelection();        
        range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

$("#text").click(function() {
    selectText(this.id);
    document.execCommand("copy");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text">
  This is text
  <span>this is another text</span>
</div>
Scroll to Top