document.getElementsByClassName doesn't work

后端 未结 2 1052
后悔当初
后悔当初 2020-12-11 13:47
function getHeight(element) {
    console.log(element);
    var offsetHeight = document.getElementsByClassName(element).offsetHeight;
    console.log(offsetHeight);
         


        
相关标签:
2条回答
  • 2020-12-11 14:17

    according to documentation https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName

    document.getElementsByClassName(classNames)
    

    returns a collection of html elements (actually instance of HTMLCollection) So If you run this code it should work

        var collection = document.getElementsByClassName(classNames),
          offset = -1;
    
        if (collection.length > 0) {
          offset = collection[0].offsetHeight;
        }
    
        return offset;
    
    0 讨论(0)
  • 2020-12-11 14:39

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

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

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

    0 讨论(0)
提交回复
热议问题