Generating fresh dynamic IDs using JavaScript

I'm working on a piece of code that generates a grid-like arrangement of chocolate pieces based on user input for the dimensions. I want each chocolate piece to have its own unique ID (like imgPos1, imgPos2, etc.), but I'm struggling to implement this functionality. Any suggestions or recommendations for third-party frameworks like React would be appreciated.

HTML (and JS):


<html>
<body>
<div>
  <form name='grid' id="grid">
<!-- Form to define the x size and y size of the grid made out of chocolate pieces -->
    Desired Length: <input type='number' name='length' min=1 max=10 step=1 value=1 id="lengthInput" />
    Desired Height: <input type='number' name='height' min=1 max=10 step=1 value=1 id="heightInput" />
    <input type='button' value='Apply' class="button_Change" />
  </form>
</div>
<div id='choc'></div>
  <template>
    <img id="imgPos" src="https://cdn.shopify.com/s/files/1/1061/1924/products/Chocolate_Bar_Emoji_large.png?" onclick='removeMe(this)' class='visible'>
  </template>
  <script type="text/javascript">
  /* Script that creates the grid by cloning the chocolate image for x:length
  and y:height */

  // defines variables q,d,form using jquery
  const d = document;
  const q = (e, n = d) => n.querySelector(e);
  const form = d.forms.grid;

// Listens for activity on the button depending on its state
document.querySelector('[type="button"]').addEventListener("click", (e) => {
    let choc = q("#choc");
    choc.innerHTML = "";

// Maxes out the values for height and length to 10 for practical reasons
    if (form.height.value > 10) form.height.value = 10;
    if (form.length.value > 10) form.length.value = 10;

    // assigns chocolate image to length and height
        for (let y = 0; y < form.height.value; y++) {
            let div = d.createElement("div");
            choc.appendChild(div);

            for (let x = 0; x < form.length.value; x++) {
                div.appendChild(q("#imgPos", q("template").content).cloneNode(true));
            }
        }
});

  function removeMe(e) {
    e.classList.remove("visible");
  };
</script>
</body>
</html>

CSS


#grid {
  top: 180px;
  left: 350px;
  position: absolute;
  cursor: auto;
  font-family: 'Press Start 2P', cursive;
  font-size: 10px;
}
#imgPos {
  display: block;
  width : auto;
  height: auto;
  cursor: pointer;
  position: relative;
  width: 20px;
  height: auto;
  top: 0px;
  left: 0px;
}
#choc {
  display: grid;
  grid-template-rows: 1fr 1fr;
  margin-left: auto;
  margin-right: auto;
  top: 240px;
  left: 340px;
  position: absolute;
  cursor: default;
}

#choc > div{
  position: absolute;
  width:50px;
  display:block;
}

#choc > div > #imgPos{
  float: left;
  float: right;
  clear:none;
  width:50px;
  display: inline-block;
}

#choc > div > #imgPos:not(.visible) {
    opacity: 0;
  cursor: default;
}

Here's a fiddle I made using it:

https://jsfiddle.net/p4ekmtgh/

Answer №1

To concatenate the id with variables x and y, you can follow this code snippet

let element = document.querySelector("#imagePosition");
let clonedChild = document.querySelector("template").content.cloneNode(true);
clonedChild.setAttribute("id", "imagePosition" + x + "_" + y);
element.appendChild(clonedChild);

The CSS should be updated accordingly as well.

For a working example, check out this JSFiddle: https://jsfiddle.net/0fhykzmw/

Answer №2

If you want to customize the ID for each iteration in your x for loop, you can use this line of code:

 document.getElementById('imgPos').id = 'imgPos_' + x
. This will concatenate the id with the current value of X on every loop.

for (let x = 0; x < form.length.value; x++) {
  div.appendChild(q("#imgPos", q("template").content).cloneNode(true));
  document.getElementById('imgPos').id = 'imgPos_' + x;
}  

It's a good idea to create a CSS class for the chocolate elements and apply it to these elements by adding the class attribute:

.imgPos {
  display: block;
  width : auto;
  height: auto;
  cursor: pointer;
  position: relative;
  top: 0px;
  left: 0px;
}

...and then assign a unique numerical ID to each chocolate element for proper styling.

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 a specific point in which we can directly pass a value to the `state` in Redux?

Is it safe to directly pass the value to the state in a redux reducer like this? export default (state = [], action) => { switch (action.type) { case 'FETCH_USER': return [...state, action.payload]; default: return state; ...

Can you create reusable components in Wordpress that are encapsulated?

In my quest to explore innovative approaches to Wordpress theme development, I have stumbled upon a variety of options such as the "Roots Sage" starter theme, the "Themosis Framework," and "Flynt." While these solutions address intriguing problems, they do ...

Button inside table cell not showing Bootstrap tooltip

I've implemented a feature where each row in a table has a button that triggers a pop-up modal when clicked. I want these buttons to display tooltips when hovered over and when focused. Below is an example of the HTML structure: <link hr ...

Using Handlebars, you can easily interpolate variables within an "each" loop

I have integrated this code into an express app that utilizes handlebars as its template engine: res.render("movies", { data: pages, arraypages:arrayPages, movie:movie}) The "arrayPages" variable is represented by an array: [ 1, 2, 3, ...

Mistakes encountered while creating a simple JavaScript slideshow featuring navigation buttons

Currently, I am attempting to create a JavaScript slideshow with both forward and back buttons. The task seems simple enough - I just need 8 images that can be navigated through by clicking the buttons. However, I am facing a frustrating issue with my code ...

Placing a table inside a div container to ensure compatibility on all browsers

Although I typically avoid using tables, I am struggling to find a better solution for setting up a page layout with a search bar, three buttons, and two hyperlinks stacked on top of each other. The challenge is to have this control centered on the webpage ...

Uninstall all packages that are no longer listed in the package.json file using Npm

Seeking guidance on how to uninstall packages from the node_modules directory that are no longer listed in package.json. These packages were removed by another developer and the package.json file has been updated on git. Any tips on how to accomplish this ...

A guide to efficiently loading all files within subdirectories via rollup, no need for those pesky require statements

I have a bunch of JavaScript files in the src/ directory that I don't want to individually require. |- /src |- a.js |- b.js |- c.js |- more.js | - index.js index.js import a from 'a.js' import a from 'b.js' import ...

Ways to prevent the repetition of keys associated with values

I am currently dealing with an array called serialNumbers, which can have different structures. For example: lot: 1 Serial: 2 lot: 1 Serial: 3 lot: 1 Serial: 4 ...or it could look like this: lot: 1 Serial: 5 lot: 1 Serial: 9 lot: 8 Serial: 2 lot: ...

Having difficulty with utilizing the sendKeys() method within the paragraph tag using Selenium WebDriver

Below is an image showing the page I want to make changes to: https://i.sstatic.net/jRtlT.png This is the HTML code snippet: <div id="taTextElement7190829193028565" class="ng-pristine ng-untouched ng-valid ta-bind" contenteditable="true" ta-bind="ta- ...

Tips for properly formatting objects in a JSON file with commas using nodejs

I have a client-server setup where I am sending right click coordinates from the client side to the server side and storing them in a JSON file. Each coordinate is stored as a separate object in the JSON file. This is an example of how my JSON file looks: ...

Streamlining the creation of JavaScript/ECMAScript array literals

Currently in the process of developing a JavaScript/ECMAScript 5.1 parser using JavaCC and encountering challenges with the ArrayLiteral production. ArrayLiteral : [ Elision_opt ] [ ElementList ] [ ElementList , Elision_opt ] ElementList : ...

What is the best way to search a map object that serves as the document ID in Firebase?

I am attempting to retrieve all fieldnames within the payload > (random doc id) objects. https://i.sstatic.net/y9703.png At this moment, my approach involves fetching other collections using the following code: async fetchPage() { const query = fir ...

Encountering a 500 Internal Server Error while attempting to redirect to the callback URL during the use of Google OAuth2 with Passportjs

The application's credentials check out. However, when the redirected URL retrieves the profile object, it returns a 500 Internal Server Error. As a result, any code within the get callback route is not functioning correctly. Any assistance on this ma ...

Tips for extracting information from a select box that is dynamically populating

I have a dropdown menu displayed in the image below. It contains a "More..." option that, when clicked, loads the next ten data items. Subsequent clicks on "More" will load another set of ten data items each time until the entire list is loaded. How can I ...

What is the best way to create an HTML5 Range that gracefully degrades?

I want to incorporate the <input type='range' /> element from HTML5 for modern browsers and fallback to a <select /> if needed. Since I am working with Ruby-on-Rails, as a last resort, I could implement something similar to this on th ...

How can we save the final composite image created with image layers, Cufon, jQuery,

I'm currently exploring the possibility of a new idea, but I'm not entirely certain if it can be achieved. My progress so far involves loading an image from a URL and using jQuery UI draggable feature to enable users to drag HTML text (which has ...

Is there a way for me to designate a specific font for a text?

Is there a way to set the font "lulyupc" for text in my webpage? Do I need to use font-family property? I have tried using it but it doesn't seem to work. How can I apply this particular font correctly? Should I include the following code in my CSS ...

Tips on retrieving PHP variable values along with HTML response using AJAX in PHP

I am looking to retrieve 2 variables: 1) The total number of records from the mysqli query performed in search_members.php 2) A boolean value indicating whether any results were found Below is the code I have written: <input type="button" value="Sea ...

Error: "Illuminate\Database\QueryException" - Unable to locate column with ID 1054 in Laravel 8

To edit data, it needs to be displayed in a form. The primary key in my database table is called id_casting. Below is the code snippet: Script : $(document).on('click', '.edit', function(){ var id = $(this).attr('id&a ...