本文介绍了document.getElementsByClassName不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function getHeight(element) {
    console.log(element);
    var offsetHeight = document.getElementsByClassName(element).offsetHeight;
    console.log(offsetHeight);
}
getHeight("card-1");

尽管它仅使用 document.getElementsByClassName(element)即可将元素正确打印到控制台,但即使使用 document.getElementsByClassName(element)[0] .offsetHeight

Although it correctly prints the element to the console with just document.getElementsByClassName(element) but I can't get to the offsetHeight property, even with document.getElementsByClassName(element)[0].offsetHeight

我必须运行循环吗?

推荐答案

document.getElementsByClassName(element)返回元素的 HTMLCollection .集合没有 offsetHeight 属性,集合中的每个元素都有.

document.getElementsByClassName(element) returns a HTMLCollection of elements. The collection doesn' t have an offsetHeight property, each element in the collection has.

现在,如果要获取第一个匹配元素的 offsetHeight ,则只需使用
document.getElementsByClassName(element)[0] .offsetHeight

Now if you want to get the offsetHeight of the first matched element you can simply use
document.getElementsByClassName(element)[0].offsetHeight

如果您想要所有匹配元素的最大或最小 offsetHeight ,则需要遍历集合.

If you wanted the max or min offsetHeight of all the matched elements you'd need to iterate over the collection.

这篇关于document.getElementsByClassName不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 21:31