javascript - 空元素和 getElementsByClassName
问题描述
我尝试解析网站,但我遇到了问题。当我用空元素解析表时
type = elements[i].getElementsByClassName("listing-item__type");
我有这个
VM56462:7 Uncaught TypeError: Cannot read property 'innerText' of undefined
at <anonymous>:7:25
如何解决?是否可以检查元素是否为空?
解决方案
因为getElementsByClassName
返回一个数组,所以不能把数组当作DOM元素,需要获取索引并使用
if (type[0] != undefined && type[0].innerText){
// add code here
}
推荐阅读
- svn - SVN 相当于 git log --name-status
- javascript - 有没有办法在 click() 事件完成后识别和执行代码?
- javascript - 如何使自定义装饰器对 vue.js 2 应用程序全局可用?
- javascript - Envify 不替换我的环境变量
- javascript - 如何在按钮单击时更改地图元素的高度?
- xcode - Xcode 不断给出未找到架构 arm64 的符号
- javascript - 如何获取字符的 Unicode 属性?
- algorithm - 如何确定桶排序的平均和最坏情况空间复杂度
- javascript - 如何使 XMLHTTPRequest 在 Internet Explorer 11 上正常工作
- c# - 如何在自己的索引上从 .NET Core Web API 登录到 Elasticsearch