首页 > 解决方案 > 空元素和 getElementsByClassName

问题描述

我尝试解析网站,但我遇到了问题。当我用空元素解析表时

type = elements[i].getElementsByClassName("listing-item__type");

我有这个

VM56462:7 Uncaught TypeError: Cannot read property 'innerText' of undefined
    at <anonymous>:7:25

如何解决?是否可以检查元素是否为空?

标签: javascripthtmlparsing

解决方案


因为getElementsByClassName返回一个数组,所以不能把数组当作DOM元素,需要获取索引并使用

if (type[0] != undefined && type[0].innerText){
// add code here
}

推荐阅读