Find the parent element with the least physical space occupied by child elements

When given multiple container <divs>, each with a number of child <divs> of varying dimensions, I want to work out which container has the least area covered by child elements.

<div class="container" id="first">
    <div class="small">This is a message</div>
    <div class="medium">This is a message</div>
    <div class="large">This is a message</div>
</div>

<div class="container" id="second">
    <div class="large">This is a message</div>
    <div class="large">This is a message</div>
    <div class="large">This is a message</div>
</div>

Example styles:

.container { width: 1000px; height: 1000px }

.small { width: 100px; height: 50px }
.medium { width: 200px; height: 100px }
.large { width: 400px; height: 200px }

Background: Users can post a message (child <div>) to a notice board (parent container <div>) and I want to highlight the “most empty” notice board.

I just need help with the logic, I can probably code it from there

Answer

You can calculate the area by multiplying the element’s offsetWidth by its offsetHeight.


Declare two variables, smallest, for storing the smallest element, and smallestArea, for storing the area of the smallest element.

Then, select all elements with the container class and loop through each one. Check if the area (calculated by multiplying the offsetWidth and offsetHeight of the element’s children) is smaller than smallestArea. If it is, we know it is smaller than the current value of smallest, so we assign the current element to smallest and the area to smallestArea.

After iterating through all the elements, smallest will be the element with the smallest area.

const containers = document.querySelectorAll('.container');

var smallest;
var smallestArea;

containers.forEach(e => {
  let area = [...e.children].reduce((a,b) => a += b.offsetHeight * b.offsetWidth, 0);
  if (!smallestArea || area < smallestArea) {
    smallest = e;
    smallestArea = area;
  }
})

console.log(smallest)
.container{width:1000px;height:1000px}.small{width:100px;height:50px}.medium{width:200px;height:100px}.large{width:400px;height:200px}
<div class="container" id="first">
  <div class="small">This is a message</div>
  <div class="medium">This is a message</div>
  <div class="large">This is a message</div>
</div>

<div class="container" id="second">
  <div class="large">This is a message</div>
  <div class="large">This is a message</div>
  <div class="large">This is a message</div>
</div>