Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
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 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!