Changing the entire contents of an array through innerHTML manipulation

I've encountered a strange issue with my Javascript code. I'm trying to create a table row using document.createElement("tr") and an array of cells like this:

cell = new Array(3).fill(document.createElement("td"));

However, when I populate the cells one by one using the innerHTML property, it seems to affect the entire array. Here's the code snippet:

row = document.createElement("tr");
cell = new Array(3).fill(document.createElement("td"));

cell[0].innerHTML = "Cat";
cell[1].innerHTML = "Dog";
cell[2].innerHTML = "Alligator";

row.appendChild(cell[0]);
row.appendChild(cell[1]);
row.appendChild(cell[2]);
myTable.appendChild(row);

The output shows:

cell[0] => "Alligator"
cell[1] => "Alligator"
cell[2] => "Alligator"

Why does assigning innerHTML to one cell change all cells in the array?

Answer №1

The issue arose from the use of 'filll', which resulted in the same td being duplicated. A solution is to generate an independent td element for each item.

ligne = document.createElement("tr");
var datas = ['Chat', 'Chien', 'Alligator'];
for(var i=0; i<datas.length; i++) {
    var td = document.createElement("td");
    td.innerHTML = datas[i];
    ligne.appendChild(td);
}

maTable.appendChild(ligne);

Answer №2

The issue at hand pertains to:

cellule = new Array(3).fill(document.createElement("td"));

The problem arises from creating an array with 3 identical td elements. Consequently, modifying the element at index 0 will affect those at index 1 and 2, as they point to the same memory location.

To rectify this, a solution is to manually construct an array using a for loop, pushing distinct references of the element into the cellule array.

Refer to the following example:

var maTable = document.getElementById("myTable");
var ligne = document.createElement("tr");

var cellule = [];
for(var i = 0; i < 3; i++) {
  cellule.push(document.createElement("td"));
}

cellule[0].textContent = "Cat"; // use textContent instead of innerHTML if only adding text
cellule[1].textContent = "Dog";
cellule[2].textContent = "Alligator";

ligne.appendChild(cellule[0]);
ligne.appendChild(cellule[1]);
ligne.appendChild(cellule[2]);
maTable.appendChild(ligne);
<table id="myTable" border="1"></table>

Answer №3

fill inserts the same element (with the same reference) into your array.

You have the option to add your elements in a different way, such as

cellule = [];
for (let i = 3; i--;) {
  cellule.push(document.createElement("td"));
}

or

cellule = new Array(3);
for (let i = cellule.length; i--;) {
  cellule[i] = document.createElement("td");
}

Answer №4

When the fill method is given an object, it will duplicate the reference and populate the array with references to that same object.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill#Description

Here is an example demonstrating how this can be achieved:

    cells = new Array(3).fill("")
    cells.forEach((el,index) => cells[index] = document.createElement("td"))
    cells[0].textContent = "Cat"; 
    cells[1].textContent = "Dog";
    cells[2].textContent = "Crocodile";
    console.log(cells[0].textContent);
    console.log(cells[1].textContent);
    console.log(cells[2].textContent);

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

Pause jQuery at the conclusion and head back to the beginning

As a beginner in the world of jQuery, I am eager to create a slider for my website. My goal is to design a slideshow that can loop infinitely with simplicity. Should I manually count the number of <li> elements or images, calculate their width, and ...

NodeJS npm module installed globally is unable to run the main/bin JavaScript file using node command

Here is an example of my package.json: { "name": "example-module", "version": "1.0.0", "bin": "./bin/example-module.js", "main": "./bin/example-module.js", "description": "Example module description", "homepage": "http://my.home.page.com", " ...

The code threw an error stating: "Error: Unable to set a new value to the unalterable property 'children' of the object '#<Object>'"

Encountering internal server error in Next.js build with Docker when reloading all routes with getServerSideProps react: "17.0.2" next: "^11.1.2" Local setup and deployment without Docker works fine, but with Docker implementation, reloading pages leads ...

Post request in ExpressJS fails to redirect user after submission

My current project involves developing a web application using NodeJS and ExpressJS. One issue I am encountering is with the login functionality on my website. After filling out the login form, the user's credentials are sent via a post request to the ...

Tips for crafting interactive Dropdown menus

Visit this link for more information Hello all, I am a beginner in HTML and Javascript and seeking guidance on how to create dynamic dropdown menus similar to the ones on the provided website. I have successfully implemented the source code, but my questi ...

I am looking to integrate my information into the user interface using Angular

import { Component, ViewEncapsulation } from '@angular/core'; import { Router } from '@angular/router'; import { Batch } from '../../../config/batchnew/batch.model'; import { BatchService } from '../../../config/batchnew ...

Neglecting to include an HTTP header

I am attempting to create an HTTP request with an Authorization header: $.ajax({ type: 'GET', url: "https://subdomain.domain.com/login", beforeSend: function (xhr) { xhr.setRequestHeader ("Auth ...

Transform the event information based on specific configuration settings

I possess an array containing JSON data named config. var config = [ [{'state': 'step1'}], [{'state': 'step2'}] , [{'state': 'step3'}] ]; The data ...

Handling Json data by parsing it and storing it into a MySQL database

I am utilizing Mandrill for handling inbound emails. To see the format of incoming email webhooks posted by Mandrill, you can refer to this link: Furthermore, here is the unformatted content I receive in the $_REQUEST variable: [{\"event\":&bsol ...

Enable users to input their custom code and run it when the specified conditions are met

Currently, I am developing a Multi-tenant application that requires users to input their own code and run it under specific conditions. I have several ideas in mind, but I am unsure which approach would be most effective. All the proposed methods will ha ...

Capture each touchdown and convert it to currency format

As a novice in the field of JS, I have put in a lot of effort into learning from various sources such as websites, documentation, friends, and other questions on Stack Overflow. However, despite all my efforts, I seem to be stuck at this point. $(docume ...

Generating option list from API JSON responses

I am currently developing a news app using React. I have set up my API to fetch data from newsapi.org and my goal is to display the available news source options in a dropdown list within my select component. However, instead of listing all news sources w ...

The function is triggered only on resize, not on initial load

Is there a way to ensure that the carouselPartialView function runs automatically when the page loads? I've noticed that it doesn't run when directly called, but works fine when called with the resizeWitdthOnly function. How can I make sure it ru ...

In JavaScript, creating a new array of objects by comparing two arrays of nested objects and selecting only the ones with different values

I've been struggling to make this work correctly. I have two arrays containing nested objects, arr1 and arr2. let arr1 =[{ id: 1, rideS: [ { id: 12, station: { id: 23, street: "A ...

Obtain the JSON object by provided criteria

In the given JSON data, how can I access an object based on the provided applicationName? { "apps": [ { "applicationName": "myTestApp", "keys": [ { "key": "app-key", ...

JavaScript - AngularJS HTML parser

I am working with an array that contains content along with HTML tags, and here is the code snippet: for (car in cars.parking[0]){ content.push('<br />'); for (token in cars.parking[0].now) { content.pus ...

Trigger a series of child functions upon clicking the parent button

I am facing an issue where I am attempting to trigger the functions of each child component from a button click event on the parent component. I have tried using props and setting up a new function in the componentDidMount lifecycle method, but only the la ...

Encountering difficulties during the migration process from a JavaScript to a TypeScript React Component

I've encountered some challenges with configuring TypeScript in my project. Initially, I developed my application using plain JavaScript. However, eager to learn TypeScript, I decided to convert my JavaScript project into a TypeScript one. To achiev ...

Determining the availability of a remote source in React: A step-by-step guide

Is there a way to verify the existence of a remote resource, such as a large zip file, without actually downloading the file? What is the most efficient method for checking the presence of the resource? ...

AngularJS: dependent dropdown menus

Attempting to create a cascade dropdown in Angular, I assumed it would work seamlessly with binding. Here is the code snippet: <select name="client" ng-model="selectedRequest.client" ng-options="c.name for c in clients track by c.id" req ...