Search code examples
javascriptjquerygreasemonkey

Copy innerHTML to clipboard from multiple <li> elements


I'm trying to create a greasemonkey script to copy the innerHTML of some <li> elements, but I'm unable to to so because it is a nodelist.

var list = document.querySelectorAll(".bx li");
GM_setClipboard(list.innerHTML)

Solution

  • Iterate and generate the combined result.

    var list = document.querySelectorAll(".bx li");
    GM_setClipboard(
      // convert nodelist to array
      // for older browser use [].slice.call(list)
      Array.from(list)
      // iterate and get HTML content
      .map(function(e) {
        return e.innerHTML;
      })
      // combine the HTML contents
      .join('')
    )
    

    Alternatively, we can use simply for loop which would be better since we don't need to create an extra array.

    var list = document.querySelectorAll(".bx li");
    
    // initialize string variable for HTML
    var html = '';
    
    // iterate over the nodelist using for loop
    for (var i = 0; i < list.length; i++) {
      // append the HTML content to the string variable
      html += list[i].innerHTML;
    }
    
    GM_setClipboard(html);