Using .setAttribute within a for-loop in JavaScript does not function as intended

I have encountered a minor issue with my JS-Script. I attempted to assign each element in an array a unique number, and these numbers were stored in another array. Initially, everything worked perfectly outside of the for-loop.

var i = 0;
document.getElementsByClassName("MosaikBilder")[i].setAttribute("value", BilderListe[i]);

However, once I placed this code snippet inside a for-loop, the entire script became unresponsive. The browser failed to load the script altogether.

var AlleBilder = document.getElementsByClassName("MosaikBilder");
for(i=0; i<AlleBilder.length -1; i++){
    document.getElementsByClassName("MosaikBilder")[i].setAttribute("value", BilderListe[i]);
}

To provide more context, here is the corresponding HTML and CSS:

HTML:

<div class="padding"></div>
<img class="MosaikBilder" src="B1.png" value=0 >
<img class="MosaikBilder" src="B2.png" value=0 >
<img class="MosaikBilder" src="B3.png" value=0 >
<img class="MosaikBilder" src="B4.png" value=0 >
<img class="MosaikBilder" src="B5.png" value=0 >
<img class="MosaikBilder" src="B6.png" value=0 >
<div style="clear: both"></div>
<div class="padding"></div>

The CSS:

    title {
        display: none;
    }

    .padding {
        width: 100%;
        height: 200px;
        background-color: red;
        margin-top: 20px;
        margin-bottom: 20px;
    }

    .MosaikBilder {
        margin: 10px;
        float: left;
    }

BilderListe is a regular array, filled by the following Javascript function:

function Zahlenzuweisung(){
    for(var i=0 ; i<BilderListe.length; i++){
        BilderListe[i] = Math.round(Math.random()*1000);
        if(BilderListe[i] > 1000){
            BilderListe[i] = 1000;
        }
    }

The array contains 15 randomly generated numbers and appears to be functioning correctly. All operations performed on the array work as intended.

Do you have any insights into why the script fails to execute when the single line of code is placed within the for-loop?

Your assistance would be greatly appreciated. As someone new to this, I am thankful for any help provided :)

EDIT: Here is the Fiddle. It's my first attempt, so there may be some errors present: https://jsfiddle.net/ugdb1423/6/

Note: The concept behind the script is to rearrange the images every time the page is loaded. I initially created a list of random non-repeating numbers. Once this was achieved, I aimed to gather all pictures in a list and assign them one of the random numbers. Following that, I planned to sort the list, remove the pictures, and reinsert them in the new order. To store the assigned random numbers, I chose to use the "value" attribute. While it seems to function outside of the for-loop, it fails inside.

Answer №1

I was a bit confused about how the 'BilderListe' array was being generated, but if you want to create an array with 15 randomly generated numbers, each ranging from 1 to 1000, you can do so within the 'Zahlenzuweisung' function using this code snippet:

var BilderListe = [];

for (var i = 0; i < 15; i++) {
  var num = Math.round(Math.random()*1000);
  if(num > 1000){
    num = 1000;
    BilderListe.push(num);
  } else {
    BilderListe.push(num);
  }
}

Then, you can use the following script to update the values of each image:

var AlleBilder = document.getElementsByClassName("MosaikBilder");
for(i=0; i<AlleBilder.length -1; i++){
  AlleBilder[i].setAttribute("value", BilderListe[i]);
}

Just remember to include this code snippet within the 'Zahlenzuweisung' function because the 'BilderListe' array is locally declared within it. If you need to access it globally, declare it outside the function like this:

var BilderListe = [];

This will allow you to utilize the 'BilderListe' array throughout your code.

Answer №2

Issue discovered:

The problem was actually with the last function displayed in the code snippet. I'm not sure why, but it seems that using AlleBilder within the function caused some complications.

Big thanks to all those who provided assistance! :)

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

What is the best way to overlook content-encoding?

I am in need of downloading a file from a device. Sometimes, the file might have an incorrect content-encoding, specifically being encoded as "gzip" when it is not actually compressed in any way. When the file is properly gzipped, retrieving the content u ...

Choose a particular form when the dropdown option is changed

I have two forms that I would like to display based on the selection from a dropdown menu. For example, if "Form1" is selected from the dropdown, then Form1 should be displayed. If "Form2" is selected, then Form2 should be displayed. Can anyone suggest h ...

The Bootstrap modal seems unable to bring the button back

Despite my code functioning properly, the button is not going backward after being clicked. Check out my output here <a href="#myModal" role="button" class="btn btn-large btn-primary" data-toggle="modal">Launch Demo Modal</a> Here is the HTML ...

Step-by-step guide for setting up CodeMirror

I'm feeling a bit lost with what to do next: <link rel="stylesheet" href="lib/codemirror.css"> <script src="lib/codemirror.js"></script> <script> var editor = CodeMirror.fromTextArea(myTextarea, { mode: "text/html" }); ...

Analyzing input from the user for string comparison

I am trying to create a code that activates when the user inputs a specific symbol or string. The issue is that it seems to be disregarding the if statements I have implemented. Here is the challenge at hand: Develop a program that can determine the colo ...

How can CSS be used to create rounded corners on an entire webpage?

Looking for advice on how to enhance the appearance of my Progressive Web App (PWA) on devices with a "notch". I have sketched out the design with red arrows. If you need to inspect the CSS classes, you can visit my website at . I am seeking recommendation ...

Update the useState value whenever I input something into the input field

I am currently working on this code snippet Whenever I make a change to my input, I want the state to change accordingly, which will update the URL However, every time this happens, an error is displayed Is there an alternative for onKeyPress that actua ...

Utilizing an NPM package in your project

Trying to incorporate a node module called "tagify" into my node.js application has been challenging. Following the instructions in the package's readme file (https://www.npmjs.com/package/@yaireo/tagify#installation), I executed the setup steps as ou ...

What is the reason behind BeautifulSoup continually reminding me to upgrade my browser?

Trying to extract the leaderboard table from the PGA Tour website using bs4. As a newcomer to HTML and Python, I have been following tutorials with sample websites where everything works fine. However, when I attempt to run the following code: from bs4 imp ...

Encountering an Error when attempting to read and update with Knex.js

I am attempting to sequentially perform read and update operations. Initially, I retrieve data from the database using the id, then I modify it and aim to update the data in the database as well. However, I encounter an error stating "Unhandled rejection E ...

vite.config.js failed to be loaded due to an error

Following the Vue docs, I decided to create a new Vue app using these steps: npm init vue@latest npm install After setting everything up, I attempted to run npm run dev, but encountered an issue. https://i.sstatic.net/Q22IX.png Here are my environments ...

Preventing Content Changes When Ajax Request Fails: Tips for Error Checking

I was struggling to find the right words for my question -- My issue involves a basic ajax request triggered by a checkbox that sends data to a database. I want to prevent the checkbox from changing if the ajax request fails. Currently, when the request ...

What is the method for absolutely positioning an element with separate targets for the `left` and `right` properties?

Seeking a complex CSS result that may seem impossible. Consider the following scenario: <div class="div1"> <div class="div2"> <div class="div3"> <div class="div4"></div> ...

Converting JSON data into a serialized format using Python and Django

I'm facing an issue where I need to serialize the entire data set from the profile page, but the problem is that the output data I receive contains single quotes instead of double quotes, making it difficult to parse later on: View: def profile_page( ...

Can you explain the significance of the v-on="..." syntax in VueJS?

While browsing, I stumbled upon a Vuetify example showcasing the v-dialog component. The example includes a scoped slot called activator, defined like this: <template v-slot:activator="{ on }"> <v-btn color="red lighten-2" ...

Struggling to iterate through the children of a variable with the help of express-handlebars?

Currently, I am in the process of developing an application using Javascript along with express, express-handlebars, and MySQL. One of my main tasks is to establish a route that follows the pattern '/viewowner/:ID/scoreboards/:year' where ID sig ...

Implement jQuery plugin selectively in AngularJS on particular pages

Struggling with Angular JS and trying to integrate the Liquid Slider jQuery Plugin. While I find Angular JS intriguing, I still have a lot to learn before fully utilizing it. Any assistance would be greatly appreciated. The objective: Implementing the Liq ...

What is the reason that I have to submit my mapped function twice in order for the updated state to show after modifying the array content?

When I try to display an image for the current value in the array item, the image does not display when I submit my value. I have to submit twice to display the value. Additionally, when changing the value and pressing submit, the content in the div does ...

Retrieve childNodes of the Select All input using jQuery from the container node with the class name "container"

I am trying to retrieve the text value of all the childNodes within the container of the corresponding input when the Select All checkbox is checked. Currently, my code captures the text inside each input label. However, it only logs the label (e.g. &apos ...

CSS Hack: Changing a Single Value with HSL Color Palette

Can specific values be adjusted using hsl? Such as changing saturation or lightness while keeping the hue constant? .red { background-color: #ff0000; /* or, hsl(0,100%,50%); */ } .red-dark { // Increase saturation by +10% and decrease lightness by - ...