Issue encountered when utilizing a for-loop in conjunction with document.getElementByClassName

Attempting to selectively apply padding to specific boxes on the left and right is proving challenging. The code isn't recognizing the "getElementByClassName" part as expected. When I execute the script, I receive an alert for "Test1" but not "Test2," indicating a potential issue with that particular line.

<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>

The values of numProducts, i, and x are being correctly retrieved, eliminating them as potential culprits. Any insights on what steps I should take next would be greatly appreciated. Thank you.

Answer №1

The correct method to use is document.getElementsByClassName, not document.getElementByClassName.

Answer №2

This is my revised version of your script. I highly suggest utilizing jQuery, since you have already loaded it. By using jQuery, functions like document.quersSelectorAll() become unnecessary.

$('.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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Placing an Image in the Right Corner Using jQuery Mobile

I am currently developing a mobile app and I need to align three images one below the other at the right corner next to some text. Any suggestions would be greatly appreciated. Thank you in advance. Below is my code snippet: <div> <ul data-r ...

Assign a different color to every other pair of rows

Here is the current table I am working with: <table> <tr> <td>a</td> </tr> <tr> <td>b</td> </tr> <tr> <td>c</td> </tr> <tr> ...

Passing data between parent and child components within an Angular application using mat tab navigation

I am currently working on a project, which can be found at this link. Current Progress: I have implemented a mat tab group with tabs inside the app-component. When a tab is clicked, a specific component is loaded. Initially, most of the data is loaded in ...

Secure a RESTful API with a Keycloak access token in a Node.js environment

I have implemented a REST API in Node.js and integrated the keycloak-connect npm package for security. I have configured the Node.js middleware to work with the keycloak middleware. var express = require('express'); var router = express.Router(); ...

I am interested in using the split method to separate and then mapping an object in JavaScript

Need assistance on separating an array using the split method. The array contains objects with properties such as name, course1, course2, and course3. Only the courses with text in their content along with a plus sign should be separated into an array usin ...

The personalized directive does not respond to modifications in attributes

I am in the process of creating a modal directive that will be used to display data tables. The directive has an attribute called modal-visible, which is initially set to false by default. If this value is true, the modal will be visible when loaded. Howev ...

When the response is manually terminated, the next middleware layer in express.js is invoked

I recently noticed an unusual occurrence: Even though I am explicitly ending the request using res.json() in one express middleware, the request still cascades down to the next middleware. It is important to mention that I am not utilizing next() anywhere ...

My Angular JS http.get request is failing to reach the specified URL

While working with AngularJS to integrate RESTful web services into my website, I am encountering an issue where I am consistently receiving errors instead of successful responses. I have been stuck on this for the past three days and any assistance would ...

Having trouble with submitting an Ajax form to a MySQL database

My expertise lies in PHP and HTML, but I'm currently learning JavaScript. I'm facing a challenge with creating a form that can submit data to be inserted into MySQL without reloading the page (using AJAX). Here is the form I have: <form id=" ...

ng-bind with the ability to store its own internal value

My server side code (GSP) is dynamically generating HTML for me in the following format: <span> <g:generateAmount /> </span> I am integrating this into an Angular controller and I want to be able to bind a scope variable to the span ...

Determine whether a request is for CSS or JavaScript when using NodeJS and Express

My routing configuration includes the following setup: app.get('*', function (req, res, next) { req.xhr ? next() : res.render('layout/layout'); }); The idea behind this is to return the base layout if the request is not an XMLHttp ...

The makeStyles feature is currently not functioning properly in the latest version of Next.js with Material UI v5

Currently, I am utilizing nextjs along with material ui in my project "@mui/material": "^5.0.1", "@mui/styles": "^5.0.1", Below is the code snippet of my component structure import { AppBar, Toolbar, Typography, Box ...

How about removing unnecessary and repetitive code?

My code needs cleaning up due to issues reported by Code Climate. The jQuery code I have is too repetitive. How can I improve it? var angle = 0; $('.rotate-receipt').on('click', function () { var index = $(this).data('button- ...

Understanding and aggregating data from JSON files

I am in possession of a group of json values outlined below {"labels":[ "time", "softirq", "user", "system", "nice", "iowait" ], "data":[ [ 1490088352, 0, 14.64646, 3.53535, 0, 1.0101 ], [ 1490088351, 0, 27.77778, 3.0303, 0, 0 ], [ 1490088350, 0.49751, 12 ...

Click on the link to see the jQuery effect in action

I'm trying to achieve a fade-out effect on the current page followed by fading in a new one. The fade-in effect is working fine, but when I click on the link, the new page loads without first fading out the existing content. The div that I want to app ...

What is the best way to showcase content without triggering a file download during a GET Request?

I recently created a webpage that showcases API responses in a neat tabular format. The technologies I used for this project were Angular JS, Servlets, and Java-Rest Assured framework. Each entry in the table includes a link to a log file, which is provid ...

What benefits and drawbacks come with setting up JS libraries in resource files compared to package.json?

Configurations for JavaScript libraries such as Babel, Nyc, Eslint, and many others can be specified in resource files or within the package.json. For example, Babel can be set up in a .babelrc file or through a babel entry in the package.json. What are ...

Tips for changing input field type from "password" to "text" in Angular?

Is there a way to dynamically convert an input field with type="password" to type="text" in Angular? In my demo, I have two input fields labeled Mobile no and Re-enter mobile number. I want these fields to change to type="text" if the user inputs the same ...

Tips for recognizing when AJAX content, such as images and text, has been fully loaded within a div while utilizing both AJAX and jQuery

$.ajax({ type: 'POST', url: 'show-photo3.php', data: 'type='+type+'&count='+count+'&aid='+aid, dataType: 'html', success: function(response) { //alert(response ...

The Add and Update functions of an AngularJS application are malfunctioning in Internet Explorer

Encountered a situation where updates and additions in IE show results in Chrome :D // Extract category object and id from the parent $scope.addNewCategory = function (category, parentId) { $scope.resetError(); category.parentId = par ...