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

190
Vistas
document.getElementByClassName not working together with for-loop

I'm trying to make it so only some specific boxes get padding on the left and right but the code doesn't pass the "getElementByClassName"-part. I get the alert "Test1" but not "Test2" so the problem is somewhere on that line I think.

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript" >

var numProducts = $('.product').length;
for(var i = 1;i<numProducts;i++){
    var x = (i+1)/3;
    
    if(x%1=0){  
        alert("test1");
        var box = document.getElementByClassName('product')[i-1];
        alert("test2");
        box.style.paddingRight ="30px";
        box.style.paddingLeft="30px";
    }
}

</script>

I get the right values from numProducts, i and x so I don't think they are the problem. What am I supposed to do? Thanks

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

0

What you expected should be document.getElementsByClassName rather than document.getElementByClassName.

about 4 years ago · Juan Pablo Isaza Denunciar

0

The following is my version of your script. I would recommend that you actually use jQuery, as you have clearly loaded it already. And using jQuery means that something like document.quersSelectorAll() is not needed anymore.

$('.product').each(function(i){
  i%3==2 && $(this).addClass("padded")
})
.padded {padding-right:30px;
     padding-left:30px;}
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<div class="product">a</div>
<div class="product">b</div>
<div class="product">c</div>
<div class="product">d</div>
<div class="product">e</div>
<div class="product">f</div>
<div class="product">g</div>
<div class="product">h</div>
<div class="product">i</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