且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用jQuery检查HTML元素是否为空?

更新时间:2022-06-25 07:10:53

if ($('#element').is(':empty')){
  //do something
}

有关详细信息,请参阅 http://api.jquery.com/is/ http://api.jquery.com/empty-selector/

for more info see http://api.jquery.com/is/ and http://api.jquery.com/empty-selector/

编辑:

有些人指出,空元素的浏览器解释可能会有所不同。如果你想忽略不可见的元素,比如空格和换行符,并使实现更加一致,你可以创建一个函数(或者只使用它内部的代码)。

As some have pointed, the browser interpretation of an empty element can vary. If you would like to ignore invisible elements such as spaces and line breaks and make the implementation more consistent you can create a function (or just use the code inside of it).

  function isEmpty( el ){
      return !$.trim(el.html())
  }
  if (isEmpty($('#element'))) {
      // do something
  }

你也可以把它变成一个jQuery插件,但你明白了。

You can also make it into a jQuery plugin, but you get the idea.