JavaScript 中通过ID获取元素
使用 getElementById()
方法通过 id 获取元素(如果存在),例如 if (document.getElementById('my-id') !== null){}
。 该方法返回其 id 与提供的字符串匹配的元素。 如果没有元素匹配,则返回 null。
这是本文中示例的 HTML。
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">Box 1</div> <script src="index.js"></script> </body> </html>
这是相关的 JavaScript 代码。
index.js
const el = document.getElementById('box'); console.log(el); // 👉️ div#box if (el !== null) { console.log('✅ Element exists'); // 👉️ safe to work with element here } else { console.log('⛔️ Element does NOT exist in DOM'); }
我们使用 document.getElementById()
方法获取其 id 与提供的字符串匹配的元素。
如果 DOM 中没有元素与提供的字符串匹配,则该方法返回 null。
我们的 if
块仅在方法未返回 null 时运行。
如果 getElementById
返回 null,则运行 else 块。
我们还可以检查 el
变量是否存储真值,这会使我们的 if
检查更加隐含。
const el = document.getElementById('box');
console.log(el); // 👉️ div#box
if (el) {
console.log('✅ Element exists');
} else {
console.log('⛔️ Element does NOT exist in DOM');
}
在我们的 if 条件中,我们检查 el 变量是否存储了一个真值。
真实是所有不虚假的价值观。
JavaScript 中的虚假值是:
null
、undefined
、0
、false
、“”(空字符串)
、NaN(不是数字)
。
如果 getElementById()
方法返回一个元素,它返回一个对象类型的值,这是一个真值,所以我们的 if 块将运行。
另一方面,如果没有找到具有提供的 id 的元素,该方法将返回一个空值,这是错误的,因此我们的 else 块将运行。
我们还可以使用布尔值检查元素是否存在。
const elementExists = document.getElementById('box') !== null;
console.log(elementExists); // 👉️ true
if (elementExists) {
console.log('✅ Element exists');
} else {
console.log('⛔️ Element does NOT exist in DOM');
}
elementExists
变量存储一个布尔值:
-
如果
getElementById
未返回空值,则为真 - 如果方法返回 null,则为 false。
这种方法也易于阅读并且对初学者更友好,因为没有必须在幕后发生的类型强制转换——值已经是布尔值。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。