Get the sum of the outerHeight of all elements of the same class

前端 未结 9 1456
Happy的楠姐
Happy的楠姐 2021-01-03 23:46

I think this is a pretty straightforward problem but...

var outerHeight = $(\'.profile\').outerHeight();
$(\"#total-height\").text(outerHeight + \'px\');
         


        
9条回答
  •  抹茶落季
    2021-01-04 00:16

    You can use get an array of the native elements and reduce to get the sum.

    This might be cleaner because it's one line without the need to declare a variable in advance.

    const height = $('div').get().reduce((prev, curr) => prev + curr.offsetHeight, 0);
    console.log(height);
    .child1 {
      height: 30px;
      background: red;
    }
    
    .child2 {
      height: 50px;
      background: green;
    }
    
    .child3 {
      height: 10px;
      background: blue;
    }
    
    
    

    This approach can be used without jQuery of course. The [...] thing is to convert NodeList to an array of elements)

    const height = [...document.querySelectorAll('div')].reduce((prev, curr) => prev + curr.offsetHeight, 0);
    console.log(height);
    .child1 {
      height: 30px;
      background: red;
    }
    
    .child2 {
      height: 50px;
      background: green;
    }
    
    .child3 {
      height: 10px;
      background: blue;
    }

提交回复
热议问题