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
What you expected should be document.getElementsByClassName
rather than document.getElementByClassName
.
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>