当使用 document.getElementById 方法获取元素时,如果返回值为 null ,那意味着没有找到具有指定 ID 的元素。
要判断 document.getElementById 是否为空,可以使用条件语句进行检查。下面土嘎嘎小编分享一个示例:
〓〓javascript代码如下:〓〓
var element = document.getElementById('myElement');
if (element) {
// 元素存在
console.log('Element found!');
} else {
// 元素不存在
console.log('Element not found.');
}
在上面给出的代码中,我们将获取的元素赋值给变量 element ,然后通过条件语句检查它是否为真(即非 null )。如果元素存在,则打印 'Element found!' ,否则打印 'Element not found.' 。
这样,你就可以根据 document.getElementById 的返回值来判断元素是否存在,然后执行相应的逻辑。