JavaScript completely transforms the HTML code for each element in an array

I'm having trouble adjusting the inner HTML of specific "div" elements using JavaScript. When I try to change the HTML of a single element in an array, it ends up changing all elements instead.

let div_length = 2;
const divs = new Array(div_length).fill(document.createElement("div"));
divs[0].innerHTML = "Hello";
console.log(divs[0].innerHTML); // Hello
console.log(divs[1].innerHTML); // Hello

Is there a way to modify this code so that it only updates the HTML of the first element?

Answer №1

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

To achieve this, utilize Array.from()

Array.from({length:bs_length}, () => document.createElement("div"));

Answer №2

The length of your array, bs_length, is actually all the same elements. It's important to grasp the distinction between primitive/immutable values (such as 1, true, "hello") and objects (like [1, 2, 3], {foo: "bar"}, or DOM elements) in OOP languages. When using a method like fill with an element, you're essentially populating the array with references to that single element rather than creating distinct copies. The solution provided by @guest271314 offers a way to populate the array with new elements using a concise one-liner, which is akin to performing:

let bs_divs = new Array(bs_length);
for (let i = 0; i < bs_length; i++) {
  bs_divs[i] = document.createElement("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

Is there more to AJAX than just fetching a JSON file?

I am in need of using AJAX to achieve my goal. My aim is to have the content of specific subpages displayed in the HTML markup below when a particular link in a list is clicked. This data can be readily accessed from the database via the CMS's API (I ...

What is the best way to conceal an HTML element on a particular page that is already styled as (visibility: visible), but only if its child has a specific class assigned to it?

I have a grid of content and posts displayed on multiple webpages. Users can select specific items from the grid to navigate to more detailed information on another page. Each webpage has its own grid which I want to filter based on a specific class. The ...

How can one access a specific element by its id that is located within an ng-template in Angular 6?

I have a question regarding accessing a button element inside an ng-template tag using its id in the TypeScript file. How can I accomplish that without encountering undefined errors? This is what I have tried so far: HTML <ng-template #popup > ...

Tips for displaying a loader image with a centered message and preventing the bootstrap modal dialogue box from closing during an AJAX response from a PHP file

I am using Bootstrap version 3.0.0. Below is the HTML code for a Bootstrap Modal: <div class="modal fade" id="newModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> < ...

Encountering an unforeseen issue with the config.kit.methodOverride while executing Svelte

While working on a Svelte project, I recently updated it to the latest version using the migration tools provided. However, now the project doesn't seem to interact with npm as expected. When I run npm i, it installs the node modules but throws an er ...

Guide on setting up an Express application to control LED light strips with a Raspberry Pi3

After setting up a node server on my Raspberry Pi to control an Adafruit Dotstar light strip, I encountered a problem. The sequence of colors on the light strip is triggered by an HTTP request to localhost:8000/fade, causing the server to run fade.js endle ...

Craft a brief description for every individual component discovered

Is there a way to identify and shorten all elements containing a <tspan> tag to just ten characters each? For example: <tspan>Bla bla bla bla</tspan> <tspan>Bla bla bla bla</tspan> <tspan>Bla bla bla bla</tspan> ...

Identify the parent container in jQuery and exclude any click events triggered by child input checkboxes

In my jQuery Mobile application, I have a piece of jQuery code that selects the child checkbox when a li is clicked. While this functionality works well, it interferes with the default behavior of the checkbox itself, making it impossible to deselect the c ...

Is it possible to access JSON with a numeric key and receive undefined as a result?

I've been attempting to extract information from my JSON data, but I keep getting an undefined result. Here is a snippet of my JSON: { "1": "A", "2": "B", "3": "C", "4": "D", "5": "E", "6": "F", "key":"pair" } This i ...

What are the different kinds of properties that can be used in Vue.js

When working with Javascript, I can create arrays that hold different types of data elements like: var ex = ['name', 12, true]; console.log(ex); In Vue JS, when defining props for a component within a single file template, I have the option to ...

What is the best way to display a welcoming message only once upon visiting the home page?

After gaining experience working with rails applications for a few months, I have been tasked with adding a feature that displays a welcome message to users visiting the site home page for the first time, but not on subsequent visits or page reloads. What ...

Creating Layouts with Bootstrap 3

I'm exploring the codepen below in an attempt to mimic the appearance of the image provided consistently across all screen sizes. However, there are two issues that I am encountering - firstly, the green numbers on the first line which represent the d ...

How can I retrieve the handle for an item within a jQuery collection from within the success function of an .ajax() call?

I'm currently facing an issue with a jQuery ajax call that I have firing for each element in a collection identified by a specific jQuery selector. Here's a snippet of the code: $('.myClass').each(function () { $.ajax({ url ...

Connecting Bootstrap Tabs Dropdown to Website LinksIncorporating Bootstrap Tabs Dropdown Menu

Having an issue with my dropdown list in the Twitter Bootstrap tab - it's not responding when clicked. I've checked Stackoverflow for solutions but nothing has worked so far. I even tried removing the data-toggle='tab' attribute. Just ...

Best approach for retrieving and adding a large number of images when dealing with slower connections

Currently, I am retrieving 100-200 images using a combination of ajax-php-mongodb. The process involves ajax making an initial call with parameters, php on the server side locating the appropriate mongo document containing all image file ids in grid fs, fe ...

Update the second mouse click functionality using jQuery

I currently have a jQuery function integrated into my WordPress portal that manages the functionality of the menu and the display of subcategories to ensure proper mobile optimization. This code, which was created by the theme editor, handles these aspects ...

Having difficulty accessing and updating data in a database while using Discord.js

My goal is to enable staff to respond to the last direct message (DM) by using ~reply <message> instead of ~dm <userID> <message>. However, before I can do that, I need to store the user's ID in a database to identify the last person ...

Validating date parameter in Wiremock request - How to ensure dynamic date matching during testing?

Looking for some assistance in verifying that the date in a request is exactly Today. I've tried various methods from the documentation, but haven't achieved the desired outcome yet. Calling out to any helpful souls who can guide a junior QA thro ...

Creating a time-limited personal link with Django Rest Framework and React

I have a frontend application built with React Framework that I want to provide access to via a time-limited personal link, without the need for additional authentication functions. With approximately 1-2 new users per day, my proposed implementation is as ...

Replicating form fields using jQuery

I have come across many questions similar to mine, but unfortunately none of them address the specific details I am looking for. On a single page, I have multiple forms all structured in the same way: <form> <div class="form-group"> ...