Home > OS >  document.getElementByClassName not working together with for-loop
document.getElementByClassName not working together with for-loop

Time:03-06

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

CodePudding user response:

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

CodePudding user response:

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 >a</div>
<div >b</div>
<div >c</div>
<div >d</div>
<div >e</div>
<div >f</div>
<div >g</div>
<div >h</div>
<div >i</div>

  • Related