I’m creating div-elements with JavaScript and need to get their position (relative to their parent):
for(let i=1;i<=30;i++){
let e = document.createElement("div");
document.querySelector("#parent").appendChild(e);
console.log(e.offsetLeft); //returns 0
}
My CSS looks like this (visually, everything works as intended):
#parent>div{
background:#fff;
width:16%;
aspect-ratio:1/1;
clip-path:polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);
float:left;
margin:0.33333%;
}
for(let i=1;i<=30;i++){
let e = document.createElement("div");
document.querySelector("#parent").appendChild(e);
console.log(e.offsetLeft); //returns 0
}
#parent>div{
background:#fff;
width:16%;
aspect-ratio:1/1;
clip-path:polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);
float:left;
margin:0.33333%;
}
<div id='parent' />
Weirdly, offsetLeft sometimes returns the correct value when I’m refreshing the page. But most of the time, it just returns 0 for all 30 elements. When I use the console to output offsetLeft of one of the elements, I always get the correct value. So it feels like something hasn’t loaded completely while the JS runs – but I don’t see what it could be.
1