HTML DOM和Javascript:未捕获的TypeError:无法读取undefined的属性'appendChild'

问题描述 投票:1回答:2

我编写了一个功能,可以删除网站上最受欢迎的文章。我执行两次刮擦,一次用于文章图像,另一次用于文章的链接和标题。然后,我将每篇文章的图像,链接和标题合并为单独的对象。从这里开始,我的目标是将此信息写入html文档。我为每篇文章创建了一个表格行。每行有三个td:一个用于标题,图像和链接。我收到的错误如下所示。我把**放在错误出现的地方。当我尝试将表格行附加到表格时会发生这种情况。注意:这是一个小项目。我不是为了任何个人利益而抓取网站。

VM51039:35 Uncaught TypeError: Cannot read property 'appendChild' of undefined
at <anonymous>:35:46
at Array.forEach (<anonymous>)
at m_getArticles (<anonymous>:12:15)
at <anonymous>:1:1

 var m_getArticles = function(){
      var article_nameANDlink = d3.selectAll('.grid.most-popular__grid h3>a').nodes();
      var article_img = d3.selectAll('.grid.most-popular__grid picture>img').nodes();

      var combination = [];
      for (i=0; i<article_nameANDlink.length; i++) {
        var info = new Object();
        info.nameANDlink=article_nameANDlink[i];
        info.img=article_img[i]; 
        combination.push(info); 
      }
      combination.forEach(function(d, index, arr) {
        var link = d.nameANDlink.getAttribute("href");
        console.log(link);
        var name = d.nameANDlink.innerText;
        console.log(name);
        var img = d.img.getAttribute("src");
        console.log(img);



        var header = document.createElement("p");
        var title = document.createTextNode(name);
        header.appendChild(title);

        var present = document.createElement("img");
        present.setAttribute("img",img);

        var provide = document.createElement("a");
        provide.setAttribute("a",link);
        provide.innerText="Read Article";

        var nth_article = document.createElement("TR");
        nth_article.setAttribute("id","row"+index);
        document.getElementsByTagName("table")[0].**appendChild(nth_article)**;

        var within_info = document.createElement("td");
        within_info.setAttribute("id","within_info"+index);
        document.getElementById("row"+index).appendChild(header);

        var within_img = document.createElement("td");
        within_img.setAttribute("id","within_img"+index);
        document.getElementById("row"+index).appendChild(present);

        var within_img = document.createElement("td");
        within_img.setAttribute("id","within_link"+index);
        document.getElementById("row"+index).appendChild(provide);


      })

    }
javascript html dom web-scraping createelement
2个回答
1
投票

如果您的表元素已经存在,请尝试使用var传递

 var mytable = document.getElementsByTagName("table")[0];
    mytable.appendChild(nth_article);

使用js创建表格的最佳方式是相同的其他元素


1
投票

将获取的表元素存储在变量中并检查它是否未定义,如果是,则创建表元素。

© www.soinside.com 2019 - 2024. All rights reserved.