Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
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 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda