'How to get the circumscribed area of all DOM elements?

I have a lot of elements on the page. I need to draw a circumscribed rectangle that contains all DOM elements.

For that I iterate DOM elements and get rectangle:

Array.from(firstChild.children).forEach((child: Element) => {
      const rect = child.getBoundingClientRect();
});

Which props I need from rect to do that? Logically I need to get minimal x,y of left-top corner and max bottom-right corner. But how?



Solution 1:[1]

To apply a border you need to set 4 values: top, left, width and height.

Getting top and left can be easily done by finding the topmost and leftmost elements. To get the other values you should do some calculation:

width = rightmost - leftmost and height = bottommost - topmost

To get rightmost and bottommost you have to loop through all elements and get their rightmost/bottommost points with the same formula, but you need to rearrange them. Here you should keep the biggest values.

//select all elements that should be inside the rectangle
const myElements = document.querySelectorAll("div#container *")

//set initial values, I made sure they are always smaller/bigger than they will be
let Top=Infinity, Left=Infinity, Bottom=-Infinity, Right=-Infinity;
for(const i of myElements){
  //loop through the elements
  const data = i.getBoundingClientRect()
  Top = Math.min(Top, data.top)
  Bottom = Math.max(Bottom, data.top+data.height)
  Left = Math.min(Left, data.left)
  Right = Math.max(Right, data.left+data.width)
}

console.log(Top, Left, Bottom, Right) // print out the coordinates
//set the border
//I subtract 1px bacuse of the border width
const myBorder = document.querySelector("#border")
myBorder.style.top=Top-1+"px"
myBorder.style.left=Left-1+"px"
myBorder.style.width=Right-Left+"px"
myBorder.style.height=Bottom-Top+"px"
#t1{
  position: absolute;
  top: 20px;
  left: 40px;
  width: 60px;
  height: 40px;
  background-color: #000;
}
#t2{
  position: absolute;
  top: 30px;
  left: 80px;
  width: 40px;
  height: 70px;
  background-color: #111;
}
#t3{
  position: absolute;
  top: 50px;
  left: -40px;
  width: 60px;
  height: 40px;
  background-color: #800;
}
#t4{
  position: absolute;
  top: 35px;
  left: 110px;
  width: 30px;
  height: 40px;
  background-color: #444;
}
#border{
  border: solid red 1px;
  position: absolute;
}
<div id="container">
  <div id="t1"></div>
  <div id="t2">
    <div id="t3"></div>
  </div>
  <div id="t4"></div>
</div>
<div id="border"></div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1