I have implemented an infinite scroll and I need to modify the width of all elements to adjust to the display width.
the code is
var elements = document.getElementsByClassName('myDiv');
for (var i = 0; i < elements.length; i ) {
elements[i].style.width = (screen.width / 2);
}
and does not work (does not change the width of the div)
but
var elements = document.getElementsByClassName('myDiv');
for (var i = 0; i < elements.length; i ) {
elements[i].style.width = "10px";
}
works
and alert(screen.width) returns correctly the screen's width.
can someone help me ?
CodePudding user response:
Add the px
- the unit is expected
document.querySelectorAll('.myDiv')
.forEach(div => div.style.width = `${(screen.width / 2)}px`)
.myDiv { background-color: yellow; }
<div style="width:100px">Hello</div>
<div style="width:200px">Hello</div>
<div style="width:300px">Hello</div>
<div style="width:400px">Hello</div>
<div style="width:500px">Hello</div>
<div style="width:600px">Hello</div>