Search code examples
javascriptcopyclipboardline-breaks

How can I prevent javascript from copying a line break to clipboard?


I found a program that allows me to copy data from a div to the clipboard. When copied, it adds a line break even though there's no line break in my div. How can I remove any line breaks from the copy.

  function copyDivToClipboard(elem) {
    var range = document.createRange();
    range.selectNode(document.getElementById(elem));
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);
    document.execCommand("copy");
    window.getSelection().removeAllRanges();
    
}
<div id='test'>This is a test</div>

<button onclick='copyDivToClipboard("test")'>Copy to clipboard</button>


Solution

  • Instead of range.selectNode use range.selectNodeContents

    function copyDivToClipboard(elem) {
        var range = document.createRange();
        range.selectNodeContents(document.getElementById(elem));
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
        document.execCommand("copy");
        window.getSelection().removeAllRanges();
    }
    <div id="test">
      This is a test
    </div>
    
    <button onclick='copyDivToClipboard("test")'>Copy to clipboard</button>