我如何在没有 jquery 但使用 javascript 的情况下检查元素 (div) 是否为空 [英] How do i check if an element (div) is empty without jquery but with javascript

查看:21
本文介绍了我如何在没有 jquery 但使用 javascript 的情况下检查元素 (div) 是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我真的只想用javascript检查一个元素是否为空,但没有jquery.当元素为空时,代码应返回 true,当元素为空时,则相反.

比如说我有这个 div 需要检查它是否为空:

因为它是空的,代码应该返回真.但在以下情况下:

<h1>猫太棒了!</h1>

它应该返回false.

我真正需要的是检查它是否包含任何孩子.我找到了答案,你可以在评论区找到.

解决方案

好吧,这个问题似乎有一个更简单的解决方案,当我看到有人将这篇文章标记为重复时,我意识到了这一点.

你可以只使用

if(document.getElementById('foo').innerHTML.trim().length == 0) {<在这里执行的代码>}

无论如何感谢您的帮助:)

So i really just want to check if an element is empty or not with javascript but without jquery. When the element is empty, the code should return true, and the opposite when it has content in it.

Say for example i have this div that needs to be checked if it's empty:

<div id="foo">

</div>

And since it is empty, the code should return true. But in the case below:

<div id="cats">
<h1>Cats are awesome!</h1>
</div>

It should return false.

EDIT: What i really need is to check if it contains any children. I found out the answer, you can find it in the comments section.

解决方案

Well, it seems there is an easier solution to this problem, which i realised when i saw that someone marked this post as a duplicate.

You can just use

if(document.getElementById('foo').innerHTML.trim().length == 0) {
   <code to execute here>
}

Thanks for the help anyways :)

这篇关于我如何在没有 jquery 但使用 javascript 的情况下检查元素 (div) 是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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