'Find element position
I have 5 div tags with position: absolute in a container with position: relative.
I want to know the row number of each div.
div position is dynamic and can move to another row by changing left, top, ...!
How can I set 5 rows and display the row number of each div in every moment?
.container {
width: 1170px;
margin: 0 auto;
position: relative;
}
.box {
position: absolute;
background: red;
width: 300px;
height: 300px;
color: #fff;
font-size: 50px;
}
<div class="container">
<div class="box" style="top: 20px; left: 30px" id="box1">box1</div>
<div class="box" style="height:100px; top: 90px; left: 530px" id="box2">box2</div>
<div class="box" style="top: 1450px; left: 230px" id="box3">box3</div>
<div class="box" style="top: 550px; left: 630px" id="box4">box4</div>
<div class="box" style="top: 950px; left: 130px" id="box5">box5</div>
</div>
Solution 1:[1]
Here is a start
You will need to see if adjacent boxes are within the height of each other if you mean that box 1 and 2 are on the same row.
If not, then the sorted array shows you the top of each box in order
const rows = [...document.querySelectorAll(".container .box")].map(box => ({ id: box.id, top: parseInt(box.getBoundingClientRect()["top"]), bottom: parseInt(box.getBoundingClientRect()["bottom"])})).sort((a,b)=>a.top-b.top)
console.log(rows)
.container {
width: 1170px;
margin: 0 auto;
position: relative;
}
.box {
position: absolute;
background: red;
width: 300px;
height: 300px;
color: #fff;
font-size: 50px;
}
<div class="container">
<div class="box" style="top: 20px; left: 30px" id="box1">box1</div>
<div class="box" style="height:100px; top: 90px; left: 530px" id="box2">box2</div>
<div class="box" style="top: 1450px; left: 230px" id="box3">box3</div>
<div class="box" style="top: 550px; left: 630px" id="box4">box4</div>
<div class="box" style="top: 950px; left: 130px" id="box5">box5</div>
</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 | mplungjan |
