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

时间:2011-07-25 08:05:35

标签: javascript jquery

我正在尝试仅在HTML元素为空时使用jQuery调用函数。

这样的事情:

if (isEmpty($('#element'))) {
    // do something
}

18 个答案:

答案 0 :(得分:510)

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

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

修改

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

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

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

答案 1 :(得分:112)

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

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

答案 2 :(得分:57)

空格和换行符是使用的主要问题:空选择器。小心,在CSS中:empty伪类的行为方式相同。我喜欢这种方法:

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

答案 3 :(得分:25)

!elt.hasChildNodes()

是的,我知道,这不是jQuery,所以你可以使用它:

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

现在开心吗?

答案 4 :(得分:19)

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

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

答案 5 :(得分:12)

如果“空”,则表示没有HTML内容,

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

答案 6 :(得分:8)

为空而不包含文字?

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

答案 7 :(得分:6)

在简历中,有很多选项可以确定元素是否为空:

1-使用html

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

2-使用text

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

3-使用is(':empty')

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

4-使用length

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

如果你试图找出输入元素是否为空,你可以使用val

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

答案 8 :(得分:2)

另一种选择应该需要更少的工作&#34;对于浏览器而言,不是 library(rpart) library(rattle) library(rpart.plot) ### Build the training/validate/test... data(iris) nobs <- nrow(iris) train <- sample(nrow(iris), 0.7*nobs) test <- setdiff(seq_len(nrow(iris)), train) colnames(iris) ### The following variable selections have been noted. input <- c("Sepal.Length","Sepal.Width","Petal.Length","Petal.Width") numeric <- c("Sepal.Length","Sepal.Width","Petal.Length","Petal.Width") categoric <- NULL target <-"Species" risk <- NULL ident <- NULL ignore <- NULL weights <- NULL #set.seed(500) # Build the Decision Tree model. rpart <- rpart(Species~., data=iris[train, ], method="class", parms=list(split="information"), control=rpart.control(minsplit=12, usesurrogate=0, maxsurrogate=0)) # Generate a textual view of the Decision Tree model. print(rpart) printcp(rpart) # Decision Tree Plot... prp(rpart) dev.new() fancyRpartPlot(rpart, main="Decision Tree Graph") html()

children()

答案 9 :(得分:1)

Vanilla javascript 解决方案:

if(document.querySelector('#element:empty')) {
  //element is empty
}

请记住,空格会影响空,但注释不会。有关详细信息,请查看关于 empty pseudo-class 的 MDN。

答案 10 :(得分:0)

document.getElementById("id").innerHTML == "" || null

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

答案 11 :(得分:0)

您可以尝试:

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

*替换白色空格,只需加入;)

答案 12 :(得分:-1)

您在寻找jQuery.isEmptyObject()吗?

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

答案 13 :(得分:-1)

这是基于https://stackoverflow.com/a/6813294/698289

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

答案 14 :(得分:-1)

<强>的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
}

尝试使用其中任何一个!

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

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

答案 15 :(得分:-1)

试试这个:

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

答案 16 :(得分:-1)

if($("#element").html() === "")
{

}

答案 17 :(得分:-2)

换行符被视为FF中元素的内容。

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

例如:

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

在IE中,两个div都被认为是空的,在FF中Chrome只有最后一个是空的。

您可以使用@qwertymk

提供的解决方案
if(!/[\S]/.test($('#element').html())) { // for one element
    alert('empty');
}

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