Generating a continuous visual display using a dynamic div with looping animation in JavaScript

Hey there, I could really use some assistance. I am currently working on a project that involves creating 100 identical divs (rows) with four inner divs (columns) inside each one containing either an image or text. The first column in each row should have the same arrow from the first to the last row (100 rows in total).

I've attempted this multiple times but so far, I've only been able to get the arrow to display in the first row.

Here is my code, both the HTML and JavaScript:


<html>
   <head>
     <title>TODO supply a title</title>
     <link href="index.css" rel="Stylesheet"/>
   </head>
   <body>
     <div id="bodydiv"> <div id="leftdiv" >  
     <script type="text/javascript">multidivs();</script></div>
   </body>
 </html>

function multidivs(){
  var columnnames=
   ["arrowdiv","contentdiv","ccontentdiv","rcontentdiv"];//styles for 
innerdiv
   var columnids=["arrow", "content", "ccontent", "rcontent"];

   for(x=0; x<100;x++) {

     var row= document.createElement('div');
     row.className = "innerdiv";

    for(i=0; i<4; i++){
      var columndiv = document.createElement('div');
      columndiv.className =columnnames[i];
      columndiv.id=columnids[i];
     if(columndiv.className=== columnnames[0]){
        attachImage();
     }
     row.appendChild(columndiv);
   }
   document.getElementById('leftdiv').appendChild(row);

  }

 }
  function attachImage(){
    var img =document.createElement('img');
    img.className= "imgdiv";
    img.src="images/orangearrow.png";

    var par= document.getElementById('arrow');
    par.appendChild(img);
  }

Answer №1

Follow this solution to resolve your issue. The reason why you are getting null when fetching an element by id is because it has not been appended to the DOM. It's also advisable not to use the same id for multiple elements.

function createMultipleDivs() {
    var columnNames = ["arrowdiv", "contentdiv", "ccontentdiv", "rcontentdiv"];
    var columnIds = ["arrow", "content", "ccontent", "rcontent"];

    for (var x = 0; x < 100; x++) {
        var row = document.createElement('div');
        row.className = "innerdiv";

        for (var i = 0; i < 4; i++) {
            var columnDiv = document.createElement('span');
            columnDiv.className = columnNames[i];
            columnDiv.id = columnIds[i];

            if (columnDiv.className === columnNames[0]) {
                addImage(columnDiv);
            }

            row.appendChild(columnDiv);
        }
        
        document.getElementById('leftdiv').appendChild(row);
    }
}

function addImage(columnDiv) {
    var img = document.createElement('img');
    img.className = "imgdiv";
    img.src = "images/orangearrow.png";
    
    columnDiv.appendChild(img);
}

Answer №2

The issue arises from the creation of multiple div elements with the same ID of "arrow," causing a problem when attempting to retrieve the element using document.getElementById('arrow') in the attachImage() function as it will always return the first instance.

An easy fix is to pass the actual DOM object to the attachImage() function.

Here is an example:

function attachImage(par){
  var img =document.createElement('img');
  img.className= "imgdiv";
  img.src="images/orangearrow.png";

  par.appendChild(img);
}

Then, within your multidivs() function, you can call attachImage(columndiv)

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

Get JSON data through AJAX using two different methods

Help needed: JSON request issue with XMLHttpRequest var xhr = new XMLHttpRequest(); function elenco_studenti() { var url = "/controller?action=student_list"; xhr.responseType = 'text'; xhr.open("GET", url, true); xhr.onreadystat ...

Issue encountered when attempting to pass more than one route parameter in a URL path

My goal is to retrieve data based on the values of 3 fields ("nkk", "nik", and "nama"). In the voters-ctrl: getVotersByParams = async (req, res) => { const nkk = req.params.nkk const nik = req.params.nik const nama = req.params. ...

The jQuery click and load function are failing to function as expected

Currently, I am facing an issue while trying to load text from a txt document into a div using the following code: $(document).ready(function(){ $('button').click(function(){ $('#contenthere').load('Load.txt'); ...

Utilizing AJAX to create objects in Rails

Within a Rails application, there exists a User model with a one-to-many relationship to Words. The scenario involves a table with multiple items (accessible through the show action in the items controller), where each item is presented as a row containing ...

What is the best way to divide this string with jQuery?

Is there a way to use jQuery to split this specific string? "[10.072721346470422,76.32974624633789][[10.075854059674523,76.32043361663818],[10.073650930297095,76.32888793945312],[10.074918540288232,76.33090496063231],[10.073862198974942,76.33137702941895] ...

Exploring the Component API in VueJS 3 with Typescript: Learn how to assign a class to a template ref

Is there a recommended way to add/remove CSS classes from a template ref using the Vue 3 Composition API and typescript? When trying to use modal.value, I encountered the following typescript errors: const modal = ref(null) results in Object is possibly ...

The image format conversion feature using Cloud Storage along with Cloud Functions and Sharp is not functioning properly

While working on uploading an image to Firebase Cloud Storage, I encountered the need to resize and convert the image format to webp. To achieve this, I decided to create a trigger using Cloud Function and implement it using the Node.js Sharp library. Alt ...

Sort the data in Angular JS by one key, but ensure that results with another key set to 0 remain at the end

Here is an array of objects containing information about various car brands: $scope.cars = [ {"brand":"McLaren","price":70,"stock":0}, {"brand":"Renault","price":10,"stock":0}, {"brand":"Ferrari","price":100,"stock":3}, {"brand":"Lamborghini","pri ...

Attempting to grasp the correct method for understanding For loops

Lately, I've been diving into teaching myself Node.JS and it has been quite an enjoyable experience. However, I've hit a frustrating roadblock that is really causing me some grief. For some reason, I just can't seem to grasp the concept of F ...

A method to trigger the opening of a div tag when a button is clicked using Vue.js

<div class="input-wrapper"> <div class="mobile-icon"></div> <input class="input-section label-set" type="text" v-model.trim="$v.mobile.$model" :class="{'is-invalid': ...

Utilizing jQuery to remove a class with an Ajax request

My setup includes two cards, one for entering a postcode and another with radio buttons to select student status (initially hidden). An Ajax request validates the postcode input - turning the card green if valid (card--success) and revealing the student se ...

Something strange happening with the HTML received after making a jQuery AJAX request

My PHP form handler script echoes out some HTML, which is called by my AJAX call. Below is the jQuery code for this AJAX call: $(function() { $('#file').bind("change", function() { var formData = new FormData(); //loop to add ...

Show a message popup or view based on the validation of the model

Picture an online store with multiple steps to complete during the checkout process. Whenever the customer clicks the 'next' button, it triggers the corresponding 'Action' method. This method includes a validation check to ensure that t ...

Get the values of var1 and var2 from the URL in PHP, for example: `example.php?var1

Currently, a portion of my website operates by using GET requests to navigate to profiles or pages. However, I am concerned about the scenario where a user visits someone's profile page (requiring one GET) and then clicks on a sub-tab within that prof ...

Tips for refreshing the default style of Material UI select

I'm having trouble customizing the default background color of the first menuItem in the select component. The class I need is not visible when inspecting the element, as the background color disappears upon inspection. Steps to reproduce: 1. Click ...

Creating a soft focus effect in a specific region (behind the text)

While working on my homepage created with HTML/CSS/Javascript, I have text positioned at the top left corner of the screen. The challenge arises from the fact that I am using different backgrounds sourced from Reddit, and a script randomly selects one duri ...

Utilize javascript to activate the hyperlink

Clicking the following link will open a video: <a href="<?php echo $rows['image1'] ; ?> " rel="vidbox" title="<?php echo $rows['name']." <br>".nl2br($rows['detail']) ; ?>" id="m2"><?php ...

Ways to launch numerous URLs in express.js

I am currently developing a service similar to a URL shortener. While a typical URL shortener redirects the user to one page, my service needs to open multiple URLs simultaneously. When a user clicks on a link from my website, I want it to open multiple l ...

Tips for calculating the total of an array's values

I am seeking a straightforward explanation on how to achieve the following task. I have an array of objects: const data = [ { "_id": "63613c9d1298c1c70e4be684", "NameFood": "Coca", "c ...

What factors should I consider when choosing the appropriate socket for receiving messages from a RabbitMQ queue?

I have encountered an issue while trying to connect to a queue on a remote server using Rabbit.js. Every attempt to connect results in the following error message: Error: Channel closed by server: 406 (PRECONDITION-FAILED) with message "PRECONDITI ...