How do i copy text to clipboard – cross browser

Ok so feels like i have gone down a rabbit hole of how to copy text to clipboard on here and tried a lot of suggestions

seems easy to do it for chrome but that option doesn’t work in other browsers

I have a few requirements

  • I would like to copy text to clipboard
  • to be able to copy a section of html with multiple elements
  • To work in safari and chrome at least
  • Vanilla Javascript

I have found this solution and it works except that it copies the html tags as well?

i tried changing the .innerHTML to .value on the button, but that comes back undefined

<div id="something">
  <div>first name: <span class="name">name</span></div>
  <div>Job title: <span class="job">job</span></div>
    <div>Phone number: <a href="0123456789" class="number">0123456789</a></div>
  <img class="companylogo" src="./img/example.jpg">

<button onclick="copyToClipboard(document.getElementById('something').innerHTML)">
  Copy the stuff


    /* copy function */
function copyToClipboard(textToCopy) {
  var textArea;

  function isOS() {
    //can use a better detection logic here
    return navigator.userAgent.match(/ipad|iphone/i);

  function createTextArea(text) {
    textArea = document.createElement('textArea');
    textArea.readOnly = true;
    textArea.contentEditable = true;
    textArea.value = text;

  function selectText() {
    var range, selection;

    if (isOS()) {
      range = document.createRange();
      selection = window.getSelection();
      textArea.setSelectionRange(0, 999999);
    } else {;

  function copyTo() {




thanks Hosseind600 for trying to help

but i managed to find some code that does exactly what i would like it to do. whilst ticking off the requirements i had set

its currently the second answer but highest votes How to copy text from a div to clipboard

            <div id="a" onclick="copyDivToClipboard()"> Click to copy </div>
                function copyDivToClipboard() {
                    var range = document.createRange();
                    window.getSelection().removeAllRanges(); // clear current selection
                    window.getSelection().addRange(range); // to select text
                    window.getSelection().removeAllRanges();// to deselect