Copy innerHTML to clipboard from multiple <li> elements

I am trying to create a greasemonkey script to copy innerHTML

from some elements <li>

, but I cannot do it because it is a nodelist.

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

      

+3


source to share


2 answers


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 just use a loop, which would be better since we don't need to create an additional 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);

      

+1


source


You need to go through the list and put together the required HTML string:



var list = document.querySelectorAll(".bx li");
var html = "";
for(var n = 0; n < list.length; ++n) 
   html += list[n].outerHTML;

      

0


source







All Articles