首页 > 解决方案 > 打印函数返回错误 elem.cloneNode 不是函数

问题描述

我有以下功能来打印表格,如下所示:

document.getElementById("btnPrint").onclick = function () {
 printElement(document.getElementsByClassName("printThis"));
}

function printElement(elem) {
 var domClone = elem.cloneNode(true);
                                
 var $printSection = document.getElementById("printSection");
                                
  if (!$printSection) {
    var $printSection = document.createElement("div");
    $printSection.id = "printSection";
    document.body.appendChild($printSection);
  }
                                
  $printSection.innerHTML = "";
  $printSection.appendChild(domClone);
  window.print();
}

当我运行该函数时,它返回以下错误:

未捕获的类型错误:elem.cloneNode 不是 HTMLButtonElement.document.getElementById.onclick 的 printElement 处的函数

标签: javascriptjquery

解决方案


您发送的是 aNodeList而不是 a Node,您应该修改您的第二行:

printElement(document.getElementsByClassName("printThis")[0]);

推荐阅读