如何使用 JavaScript 检查元素是否为 Div

使用 JavaScript 检查元素是否为 Div

How to Check if an Element is a Div using JavaScript

使用该tagName属性检查元素是否为 div,例如
if (div.tagName === 'DIV') {}. tagName属性返回访问它的元素的标签名称。请注意,该属性以大写形式返回 DOM 元素的标签名称。

以下是本文示例的 HTML。

索引.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">Box content</div> <script src="index.js"></script> </body> </html>

这是相关的 JavaScript 代码。

索引.js
const box = document.getElementById('box'); if (box.tagName === 'DIV') { console.log('✅ the element is a div'); } else { console.log('⛔️ the element is not a div'); }

tagName
属性返回访问它的元素的标签名称

It should be noted that DOM element names are upper-cased. For example, if
accessed on an img element, the tagName property would return "IMG".

index.js
const box = document.getElementById('box'); console.log(box.tagName); // 👉️ "DIV"

You could use the
String.toLowerCase
method to convert the tag name to lowercase.

index.js
const box = document.getElementById('box'); if (box.tagName.toLowerCase() === 'div') { console.log('✅ the element is a div'); } else { console.log('⛔️ the element is not a div'); }
This can be a bit more intuitive as readers of your code might get confused by the capitalized DIV string.

If you need to make sure that the value stored in the box variable is not
null or undefined before accessing the tagName property, use optional
chaining.

index.js
const box = null; if (box?.tagName?.toLowerCase() === 'div') { console.log('✅ the element is a div'); } else { console.log('⛔️ the element is not a div'); }
You could get a null value back if you provide a non-existent id to the getElementById method or a non-existent selector to the querySelector method.

可选的
链接 (?.)null运算符允许我们在引用指向 a或
undefined
时进行短路。

运算符没有抛出错误,而是短路返回undefined.

在上面的示例中,else块将运行。