[英]How do I check for null on a .textContent call, when the element will only be there some of the time
我有这段代码,在那里我试图检查我通过 ID 获得的元素是否不等于 null,但实际检查它是否为 null 仍然会抛出一个控制台错误,提示“未捕获的类型错误:不能read property 'textContent' of null"... 如何阻止出现此错误?
补充一点很重要,这个元素不会总是在页面上,当它不在页面上时,我不希望控制台输出该错误
var ldt = document.getElementById("ldt").textContent; if(ldt !== null) { document.getElementById("ldt").textContent = n + " " + t; };
你会想做
var ldt = document.getElementById("ldt"); // no `.textContent` here
if (ldt !== null) {
ldt.textContent = n + " " + t;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.