我有一些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>
JavaScript的:
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();
答案 0 :(得分:10)
即使您的文档查询返回一个空数组,它仍然是true
这是因为[]
是一个&#34; truthy&#34;值。
if ([]) { console.log("always true"); }
而是尝试
var elems = document.getElementsByClassName("foo");
if (elems.length > 0) {
// ...
}
如果您以后不关心访问elems
,可以跳过中间变量
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
的上下文中找到标记,而不是全局document
上下文。
答案 1 :(得分:4)
更改
if (document.getElementsByClassName('testing')){ //This will always be true
到
if (document.getElementsByClassName('testing').length){//This depends on lenght , could be 0
答案 2 :(得分:1)
这里的事情是,您使用document.getElementsByClassName(something)
创建。元素存在,但为空。因此它的长度为0 。
var el = document.getElementsByClassName('testa');
console.log(el); // []
您可以检查长度:
if(document.getElementsByClassName('testing').length > 0)
答案 3 :(得分:0)
我认为你想使用document.getElementById而不是document.getElementsByClassName。
我见过这样使用过getElementsById:
var elementExists = document.getElementById(“targetID”);
与您想要的相似。