我试图调用一个函数,只有当一个HTML元素是空的,使用jQuery。

就像这样:

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

当前回答

你可以试试:

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

*替换空格,以防万一;)

其他回答

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

如果你说的“空”是指没有HTML内容,

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

香草javascript解决方案:

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

请记住,空格会影响空,但注释不会。有关更多信息,请检查MDN关于空伪类。

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

if($.trim($("selector").html())=='')
!elt.hasChildNodes()

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

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

现在快乐吗?