Adding an interactive element to a predetermined collection

CSS

<button class='btn' data-next="games" data-prev="games1" data-storage="128" data-graphcard="2" data-processor="i3">Click Here</button>

JavaScript.

let components = ["storage", "graphcard", "processor"];
const allBtnsToStore = document.querySelectorAll('.btn');

allBtnsToStore.forEach((element, index) => {
  element.addEventListener('click', () => {
    components.forEach((item) => {
      console.log(`${element.dataset.item}`);
    });
  });
});

The main goal is to retrieve each item from the array and match it with its corresponding data in the HTML.
${element.dataset.*} where ' * ' represents items in the array.
For instance: access values of dataset storage, graphcard, and processor of the button using ${element.dataset.storage}, ${element.dataset.graphcard}, and ${element.dataset.processor}. Instead of individually specifying all items in the array, I aim to loop through them (components.forEach((item)) and dynamically replace it in ${element.dataset.item}

However, since .`${element.dataset.item}`. is encapsulated by "`", escaping after "${element.dataset.", inserting the actual item, and re-capturing becomes challenging in order to close the line with }

I experimented with variations like ${element.dataset."item"}, ${element.dataset.[item]}, or ${element.dataset.(item)} but none proved effective.

Answer №1

Yоu’rе сlоsе tо getting it right: the correct bracket notation should bе ${el.dataset[item]}, without an additional . bеtwееn dataset аnd [item]. Check out the proof-of-concept demonstration below:

let components = ["RAM", "GPU", "CPU"];
const allButtonsToClick = document.querySelectorAll('.button');

allButtonsToClick.forEach((el, i) => {
  el.addEventListener('click', () => {
    components.forEach((item) => {
      console.log(`${el.dataset[item]}`);
    });
  });
});
<button class='button' data-next="games" data-parent="games1" data-storage="128" data-graphcard="2" data-processor="i3">Click here</button>

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 it possible to iterate through various values using the same variable name in Mustache.js?

I have data structured in the following way: hello this is {{replacement_data}} and this {{replacement_data}} is {{replacement_data}}. I'm interested in using Mustache to substitute these placeholders with values from an array: [val1, val2, val3. ...

Guide to configuring browserify

After installing the modules (browserify, react, reactify), I attempted to process a JSX file using browserify. var React = require("react"); var App = React.createClass({ render: function () { return <h1>111</h1> } }); React ...

What is the process for transferring `Parentobject1` to `childobject2` and `childobject3` in Three.js?

I have created two objects doubleSquare and doubleSquare1. I was expecting the output to be Double Line Square Object, but I have tried two different formats and have not achieved the desired output. Can someone please provide me with a solution? I have lo ...

Leverage JavaScript to showcase Django object on the webpage

I am trying to achieve the following using javascript: when a row is clicked, it should retrieve the index and display the object at that index. This functionality works in a django template. <div>{{ project.0.customer_name}}</div> <div> ...

How can I switch between different images using jQuery?

HTML <div class="image_rollover"> <img id="image_one" src=image_one.png"> <img id="image_two" src="image_two.png"> <img id="image_three" src="image_three.png"> <img id="image_four" src="image_four.png"> ...

Using Vue.js as a view engine for ExpressJS

I'm on the hunt for a solution similar to React for ExpressJS, but tailored for Vue.js instead. Currently, I'm facing challenges when it comes to passing data from my database (mongoose) to my view. Right now, I'm utilizing the handlebars v ...

The integration of Zoom SDK with React and Node inevitably leads to encountering errors

I have been struggling to integrate zoomsdk into my react app and have followed all the steps mentioned here. The backend part is functioning properly, and I am receiving the signature response. However, when attempting to run the frontend portion, I encou ...

End the HTML page once the Flash (SWF) animation comes to a close

I have successfully exported my flash file to an HTML page. How can I make the page close automatically once the flash animation is finished? While I can use actionscript to stop the animation, I need the entire page to shut down on its own. I attempted u ...

Step-by-step guide on incorporating Google Fonts and Material Icons into Vue 3 custom web components

While developing custom web components with Vue 3 for use in various web applications, I encountered an issue related to importing fonts and Google material icons due to the shadow-root. Currently, my workaround involves adding the stylesheet link tag to t ...

Tips for managing unexpected TCP disconnects?

Using Node.js, I set up both a TCP server and an HTTP server. The TCP server was intended to connect with hardware devices via TCP connection. I have 100 TCP clients that are maintaining their connections with the server. Normally, when a TCP client disc ...

What is the impact of Javascript variable scope in the context of "for...in..." loops?

Imagine you have a code snippet like this: dict = {"key":"elem"} for (var elem in dict){ someFunction(function(){ anotherFunction(dict[elem]); }) } Question: Is elem still considered as the temporary variable created in the for...in... s ...

Can a function be appropriately utilized in a reducer?

For my reducer, I am looking to incorporate a function that is necessary for sorting. I have successfully imported this function from another file and it seems to be functioning correctly. However, I am unsure about the validity of importing and using fu ...

The argument supplied to the `openUri()` function should be in the form of a string, but instead, it is displaying as "undefined". Please ensure that the initial parameter provided to either `mongoose.connect()`

Encountered error: The `uri` parameter passed to `openUri()` must be a string, but it is currently set as "undefined". Please ensure that the first parameter in either `mongoose.connect()` or `mongoose.createConnection()` is a valid string. Below are the ...

Tips on updating a JSON file exclusively using vanilla JavaScript with an AJAX call using the HTTP POST method?

Question One: I have been struggling to find a way to update a JSON file using the HTTP POST method when both files are stored on the same server (e.g. Godaddy or AWS). While I am able to send data to the server successfully, the JSON file is not being upd ...

Execute Javascript to simultaneously open various links in a single action (not using popups)

I am looking to open multiple URLs with a single click event that also redirects to a specified URL. I have attempted this, but it doesn't seem to be working as intended. Here is the HTML code: <a id="mybutton" href="http://example.net/quote" onc ...

Efficiently centering content in a grid layout using automatic fit repetition for optimized responsiveness

I've implemented a responsive grid where each item has its own hidden details section that is revealed upon clicking the item. The structure of the HTML/CSS setup is as follows: <div class="grid"> <div class="item"> ...

How to prioritize indices when querying multiple indexes in Elasticsearch?

Utilizing the Elasticsearch multi index API, I am able to query across multiple indices. However, it is important for me to prioritize my queries. As an illustration, when querying in the indices index1 and index2, the syntax would look like: /index1,ind ...

The handler for errors in DRW consistently generates the message "Error" instead of providing specific information about the issue at hand

FiltersManager.getAllServices({ callback : updateServiceFilter, errorHandler : function(message) { alert(message); } }); Although I throw an exception when an error occurs in th ...

Using javascript, how can you fill in the missing dates within an array of objects?

I need to populate this object with dates starting from today up to the next 7 days. Here is my current object: let obj = { "sessions": [{ "id": 0, "available_capacity": 3, "date": "15-05- ...

Error Encountered in Vue.js when Trying to Access a Nested

Below is a snippet of my route code from app.js let routes = [{ path: "/dashboard", component: require("./components/Dashboard.vue") }, { path: "/tour", component: require("./components/Index.vue"), children: [{ name: &apos ...