// 判断元素是否存在
// 方法一:使用 document.getElementById
function isElementExistById(elementId) {
return document.getElementById(elementId) !== null;
}
// 解释:通过传入的元素 ID,使用 document.getElementById 方法获取元素,
// 如果返回值不为 null,则说明该元素存在,否则不存在。
// 示例:
// console.log(isElementExistById('myElement')); // 假设页面中有一个 id 为 'myElement' 的元素,则返回 true
// 方法二:使用 document.querySelector
function isElementExistBySelector(selector) {
return document.querySelector(selector) !== null;
}
// 解释:通过传入的选择器(可以是类名、标签名、属性选择器等),使用 document.querySelector 方法获取元素,
// 如果返回值不为 null,则说明该元素存在,否则不存在。
// 示例:
// console.log(isElementExistBySelector('.myClass')); // 假设页面中有一个 class 为 'myClass' 的元素,则返回 true
上一篇:js 判断对象是否存在
下一篇:js 对象是否包含某个属性
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站