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

时间:2021-03-16 08:41:23

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
}

17 个解决方案

#1


458  

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/emp-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插件,但是你可以理解。

#2


99  

I found this to be the only reliable way (since Chrome & FF consider whitespaces and linebreaks as elements):

我发现这是唯一可靠的方法(因为Chrome和FF认为whitespaces和linebreak是元素):

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

#3


43  

White space and line breaks are the main issues with using :empty selector. Careful, in CSS the :empty pseudo class behaves the same way. I like this method:

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

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

#4


20  

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

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

#5


19  

!elt.hasChildNodes()

Yes, I know, this is not jQuery, so you could use this:

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

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

Happy now?

现在快乐吗?

#6


10  

If by "empty", you mean with no HTML content,

如果是“空”,你的意思是没有HTML内容,

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

#7


8  

Empty as in contains no text?

空如不包含文本?

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

#8


2  

Another option that should require less "work" for the browser than html() or children():

另一种选择,应该比html()或children()需要更少的“工作”:

function isEmpty( el ){
  return !el.has('*').length;
}

#9


2  

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 -使用文本:

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

3- Using is(':empty'):

3 -使用(“:空”):

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

4- Using length

4 -使用长度

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
}

#10


1  

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

or

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

#11


0  

Are you looking for jQuery.isEmptyObject() ?

您正在寻找jQuery.isEmptyObject()吗?

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

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

#12


0  

Here's a jQuery filter based on https://*.com/a/6813294/698289

这是一个基于https://*.com/a/6813294/698289的jQuery过滤器。

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

#13


0  

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.
​

#14


0  

Try this:

试试这个:

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

#15


-1  

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

}

#16


-1  

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中,两个divs都是空的,在FF中只有最后一个是空的。

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
    }
})

#17


-1  

You can try:

你可以尝试:

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

*Replace white spaces, just incase ;)

*替换空白,以防万一;

#1


458  

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/emp-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插件,但是你可以理解。

#2


99  

I found this to be the only reliable way (since Chrome & FF consider whitespaces and linebreaks as elements):

我发现这是唯一可靠的方法(因为Chrome和FF认为whitespaces和linebreak是元素):

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

#3


43  

White space and line breaks are the main issues with using :empty selector. Careful, in CSS the :empty pseudo class behaves the same way. I like this method:

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

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

#4


20  

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

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

#5


19  

!elt.hasChildNodes()

Yes, I know, this is not jQuery, so you could use this:

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

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

Happy now?

现在快乐吗?

#6


10  

If by "empty", you mean with no HTML content,

如果是“空”,你的意思是没有HTML内容,

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

#7


8  

Empty as in contains no text?

空如不包含文本?

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

#8


2  

Another option that should require less "work" for the browser than html() or children():

另一种选择,应该比html()或children()需要更少的“工作”:

function isEmpty( el ){
  return !el.has('*').length;
}

#9


2  

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 -使用文本:

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

3- Using is(':empty'):

3 -使用(“:空”):

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

4- Using length

4 -使用长度

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
}

#10


1  

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

or

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

#11


0  

Are you looking for jQuery.isEmptyObject() ?

您正在寻找jQuery.isEmptyObject()吗?

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

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

#12


0  

Here's a jQuery filter based on https://*.com/a/6813294/698289

这是一个基于https://*.com/a/6813294/698289的jQuery过滤器。

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

#13


0  

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.
​

#14


0  

Try this:

试试这个:

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

#15


-1  

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

}

#16


-1  

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中,两个divs都是空的,在FF中只有最后一个是空的。

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
    }
})

#17


-1  

You can try:

你可以尝试:

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

*Replace white spaces, just incase ;)

*替换空白,以防万一;