How do I check if an HTML element is empty using j

2019-01-01 10:16发布

I'm trying to call a function only if an HTML element is empty, using jQuery.

Something like this:

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

17条回答
大哥的爱人
2楼-- · 2019-01-01 10:49

Empty as in contains no text?

if (!$('#element').text().length) {
    ...
}
查看更多
大哥的爱人
3楼-- · 2019-01-01 10:50
jQuery.fn.doSomething = function() {
   //return something with 'this'
};

$('selector:empty').doSomething();
查看更多
浅入江南
4楼-- · 2019-01-01 10:50

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

$.extend($.expr[':'], {
  trimmedEmpty: function(el) {
    return !$.trim($(el).html());
  }
});
查看更多
孤独寂梦人
5楼-- · 2019-01-01 10:52

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

if($('#element').html() == "") {
  //call function
}
查看更多
梦寄多情
6楼-- · 2019-01-01 10:52

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.
​
查看更多
孤独总比滥情好
7楼-- · 2019-01-01 10:53
!elt.hasChildNodes()

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

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

Happy now?

查看更多
登录 后发表回答