简体   繁体   English

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

[英]How do I check if an HTML element is empty using jQuery?

I'm trying to call a function only if an HTML element is empty, using jQuery. 我正在尝试仅在HTML元素为空时使用jQuery调用函数。

Something like this: 像这样的东西:

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

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

EDIT: 编辑:

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
  }

You can also make it into a jQuery plugin, but you get the idea. 你也可以把它变成一个jQuery插件,但你明白了。

我发现这是唯一可靠的方法(因为Chrome和FF将空格和换行符视为元素):

if($.trim($("selector").html())=='')

White space and line breaks are the main issues with using :empty selector. 使用空白选择器时,空格和换行符是主要问题。 Careful, in CSS the :empty pseudo class behaves the same way. 小心,在CSS中:empty伪类的行为方式相同。 I like this method: 我喜欢这种方法:

if ($someElement.children().length == 0){
     someAction();
}
!elt.hasChildNodes()

Yes, I know, this is not jQuery, so you could use this: 是的,我知道,这不是jQuery,所以你可以使用这个:

!$(elt)[0].hasChildNodes()

Happy now? 现在开心?

jQuery.fn.doSomething = function() {
   //return something with 'this'
};

$('selector:empty').doSomething();

If by "empty", you mean with no HTML content, 如果是“空”,则表示没有HTML内容,

if($('#element').html() == "") {
  //call function
}

Empty as in contains no text? 空如在包含没有文字?

if (!$('#element').text().length) {
    ...
}

In resume, there are many options to find out if an element is empty: 在简历中,有很多选项可以确定元素是否为空:

1- Using html : 1-使用html

if (!$.trim($('p#element').html())) {
    // paragraph with id="element" is empty, your code goes here
}

2- Using text : 2-使用text

if (!$.trim($('p#element').text())) {
    // paragraph with id="element" is empty, your code goes here
}

3- Using is(':empty') : 3-使用is(':empty')

if ($('p#element').is(':empty')) {
    // paragraph with id="element" is empty, your code goes here
}

4- Using length 4-使用length

if (!$('p#element').length){
    // paragraph with id="element" is empty, your code goes here
}

In addiction if you are trying to find out if an input element is empty you can use val : 如果你试图找出输入元素是否为空,你可以使用val

if (!$.trim($('input#element').val())) {
    // input with id="element" is empty, your code goes here
}

Another option that should require less "work" for the browser than html() or children() : html()children()相比,浏览器需要更少“工作”的另一个选项:

function isEmpty( el ){
  return !el.has('*').length;
}
document.getElementById("id").innerHTML == "" || null

要么

$("element").html() == "" || null

You can try: 你可以试试:

if($('selector').html().toString().replace(/ /g,'') == "") {
//code here
}

*Replace white spaces, just incase ;) *替换白色空间,只需更换;)

Are you looking for jQuery.isEmptyObject() ? 你在寻找jQuery.isEmptyObject()吗?

http://api.jquery.com/jquery.isemptyobject/ http://api.jquery.com/jquery.isemptyobject/

Here's a jQuery filter based on https://stackoverflow.com/a/6813294/698289 这是一个基于https://stackoverflow.com/a/6813294/698289的jQuery过滤器

$.extend($.expr[':'], {
  trimmedEmpty: function(el) {
    return !$.trim($(el).html());
  }
});

JavaScript JavaScript的

var el= document.querySelector('body'); 
console.log(el);
console.log('Empty : '+ isEmptyTag(el));
console.log('Having Children : '+ hasChildren(el));


function isEmptyTag(tag) { 
    return (tag.innerHTML.trim() === '') ? true : false ;
}
function hasChildren(tag) {
    //return (tag.childElementCount !== 0) ? true : false ; // Not For IE
    //return (tag.childNodes.length !== 0) ? true : false ; // Including Comments
    return (tag.children.length !== 0) ? true : false ; // Only Elements
}

try using any of this! 尝试使用任何一个!

document.getElementsByTagName('div')[0];
document.getElementsByClassName('topbar')[0];

document.querySelectorAll('div')[0];
document.querySelector('div'); // gets the first element.
​

Try this: 试试这个:

if (!$('#el').html()) {
    ...
}
if($("#element").html() === "")
{

}

Line breaks are considered as content to elements in FF. 换行符被视为FF中元素的内容。

<div>
</div>
<div></div>

Ex: 例如:

$("div:empty").text("Empty").css('background', '#ff0000');

In IE both divs are considered empty, in FF an Chrome only the last one is empty. 在IE中,两个div都被认为是空的,在FF中Chrome只有最后一个是空的。

You can use the solution provided by @qwertymk 您可以使用@qwertymk提供的解决方案

if(!/[\S]/.test($('#element').html())) { // for one element
    alert('empty');
}

or 要么

$('.elements').each(function(){  // for many elements
    if(!/[\S]/.test($(this).html())) { 
        // is empty
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM