检查div是否包含html元素

时间:2013-12-13 08:47:26

标签: jquery

我只是想知道如何检查div是否没有子节点,因为如果元素没有加载到指定的div中,我需要放置占位符文本。

这是我的代码:

var test = ($('#'+chartId)).children().length;
console.log(test);
if(test==""){
    alert('empty');
}
else{
    alert('present');
}

如果我正在尝试检测是否正在将闪存组件加载到div中,这是否会起作用?

3 个答案:

答案 0 :(得分:4)

.length为0,没有孩子时不为空。您也可以稍微缩短代码,如下所示:

if(!($('#'+chartId)).children().length){
    alert('empty');
}
else{
    alert('present');
}

答案 1 :(得分:4)

试试这个:

if($('#' + chartId).children().length > 0){
    alert('present');
}
else{
    alert('empty');
}

DEMO

答案 2 :(得分:0)

您所犯的错误是将长度(数字)与空字符串进行比较。如果没有任何内容并且您在其上调用.length,则它将返回0,而不是空字符串。

var length = $('#one').children().length;
if (length > 0) {
    alert('hi');
}
if (length === 0) {
    alert('bye');
}   

小提琴:http://jsfiddle.net/KyleMuir/349Uq/