JavaScript-If语句始终返回true

JavaScript-If语句始终返回true,javascript,if-statement,Javascript,If Statement,我有一些JavaScript,我想在HTML中搜索类名,然后检测该div中几个元素的高度,将它们添加到一起,并在警报中显示总高度。下面的代码似乎运行得很好,但我注意到,无论类名是什么,即使HTML中不存在该类,代码都将运行。如何重写if语句,使其仅在遇到具有指定类名的div时运行代码?我不希望它检测到错误的h1和p元素的高度。谢谢你的帮助 HTML: <div class="testing"> <h1>Understanding Scope</h1>

我有一些JavaScript,我想在HTML中搜索类名,然后检测该div中几个元素的高度,将它们添加到一起,并在警报中显示总高度。下面的代码似乎运行得很好,但我注意到,无论类名是什么,即使HTML中不存在该类,代码都将运行。如何重写if语句,使其仅在遇到具有指定类名的div时运行代码?我不希望它检测到错误的h1和p元素的高度。谢谢你的帮助

HTML:

<div class="testing">
    <h1>Understanding Scope</h1>
    <p>By understanding code's <em>scope</em>, we know when that code affects only one part of our code, or the entire codebase.  If we create things that are <em>global</em> in scope, we are giving any code the supreme power to control our code.   So we want to protect our code by being very careful when creating things that are global in scope. This is especially important if you plan on using JavaScript libraries like jQuery.</p>
</div>
<h1>Local Scope</h1>
<p>JavaScript uses <em>function scope</em>, meaning every time we create a new function the scope changes.  Any code inside that function is <em>local</em> to that function. Code that is local in scope is not accessible to outside code.</p>
function testing(){
        if (document.getElementsByClassName('testing')){
            var headerHeight = document.getElementsByTagName('h1')[0].offsetHeight;
            var textHeight = document.getElementsByTagName('p')[0].offsetHeight;
            var totalHeight = headerHeight + textHeight;


            alert(totalHeight);

        }
    }
testing();

即使您的文档查询返回一个空数组,它仍然是
true

这是因为
[]
是一个“真实”值

相反,尝试

var elems = document.getElementsByClassName("foo");

if (elems.length > 0) {
  // ...
}
如果以后不想访问
元素
,可以跳过中间变量

if (document.getElementsByClassName("foo").length > 0) // ...

根据你的评论

var div = document.getElementsByClassName("testing");

if (div.length > 0) {
  div[0].getElementsByTagName("h1")[0] ...
  div[0].getElementsByTagName("p")[0] ...
}
这将在
div
的上下文中找到标记,而不是全局
文档
上下文。

更改

 if (document.getElementsByClassName('testing')){ //This will always be true


我想您应该使用document.getElementById而不是document.getElementsByClassName

我见过getElementsById这样使用:

var elementExists=document.getElementById(“targetID”)


这将与您想要做的类似。

这里的内容是,您使用
document.getElementsByClassName(something)
创建的。因此元素存在,但它是空的。因此,它的长度为0

var el = document.getElementsByClassName('testa');
console.log(el); // []
您可以检查长度

if(document.getElementsByClassName('testing').length > 0)

这似乎只是检查div是否存在,然后继续查找整个文档的第一个h1和p元素的高度。我希望它严格地从该div中查找第一个h1和p元素。@Bryan,我提供了一个编辑来处理您的评论。这似乎只是检查该div是否存在,然后继续查找整个文档的第一个h1和p元素的高度。我希望它严格地从该div中查找第一个h1和p元素。这似乎只是检查该div是否存在,然后继续查找整个文档的第一个h1和p元素的高度。我希望它严格地从这个div中查找第一个h1和p元素。
var el = document.getElementsByClassName('testa');
console.log(el); // []
if(document.getElementsByClassName('testing').length > 0)