使用 JavaScript 检查 Span 元素是否为空

使用 JavaScript 检查 Span 元素是否为空

Check if a Span element is Empty using JavaScript

使用该childNodes属性检查 span 元素是否为空。
childNodes属性返回一个NodeList元素的子节点,包括元素、文本节点和注释。如果属性返回值
0,则跨度为空。

以下是本文示例的 HTML。

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

这是相关的 JavaScript 代码。

索引.js
const span = document.getElementById('container'); if (span.childNodes.length === 0) { console.log('✅ Span element is empty'); } else { console.log('⛔️ Span element is not empty'); }

childNodes
属性
返回一个
NodeList包含元素的子节点,包括:

  • 子元素
  • 文本节点
  • 评论节点
Accessing the length property on the NodeList returns the number of child nodes of the element.

If the length property returns a value greater than 0, then the span
element is not empty.

If your element had a text node or event a comment inside it, it would be
included in the NodeList the childNodes property returns.

If you want to ignore comments, use the textContent property to check if the
span element is empty.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <span id="container"> <!-- my comment here --> </span> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const span = document.getElementById('container'); if (span.textContent.trim() === '') { console.log('✅ Span element is empty'); } else { console.log('⛔️ Span element is not empty'); }

We used the
textContent
property to get the text content of the span element and its descendants.

We removed any leading or trailing whitespace using the trim() method and compared the result to an empty string.

如果元素的textContent属性是一个空字符串,那么它就是空的。