如何检查div元素是否为空 [英] How to check if div element is empty

查看:173
本文介绍了如何检查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 ) {

这篇关于如何检查div元素是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆