Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
javascript pass screen width to function

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 ?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Add the px - the unit is expected

document.querySelectorAll('.myDiv')
  .forEach(div => div.style.width = `${(screen.width / 2)}px`)
.myDiv { background-color: yellow; }
<div class="myDiv" style="width:100px">Hello</div>
<div class="myDiv" style="width:200px">Hello</div>
<div class="myDiv" style="width:300px">Hello</div>
<div class="myDiv" style="width:400px">Hello</div>
<div class="myDiv" style="width:500px">Hello</div>
<div class="myDiv" style="width:600px">Hello</div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda