如何检查div元素是否为空
问题描述:
可能重复:
使用jQuery检查html元素是否为空
我有一个像这样的空div:
I have an empty div like this:
<div id="cartContent"></div>
我需要检查它是否为空。如果它为空,则需要返回true,然后添加一些
元素。如果不是,则返回false并执行其他一些功能。检查div中是否有任何
元素的最佳方法是什么?
I need to check if it's empty. If it's empty it needs to return true and then some
elements are added. If not it returns false and some other function executes. What's the best way to check if there are any
elements in the div?
谢谢
答
您可以使用 .is()
。
You can use .is()
.
if( $('#leftmenu').is(':empty') ) {
或者您可以只测试 长度
属性以查看是否找到了一个:
Or you could just test the length
property to see if one was found:
if( $('#leftmenu:empty').length ) {
你可以使用 $。trim()
删除空格(如果这是你想要的)并检查内容的长度。
You can use $.trim()
to remove whitespace (if that's what you want) and check for the length of the content.
if( !$.trim( $('#leftmenu').html() ).length ) {