Converting a data-attribute list into an array

My current setup includes an image with the following properties:

<img id="img" data-list="['image2.jpg', 'image3.jpg', 'image4.jpg']" src="image1.jpg">

I am wondering how I can extract the list of images from the data-list attribute and save it to an array variable. Any suggestions?

Answer №1

Retrieve information from the img element, format it into JSON, and then utilize JSON#parse to convert it into an array:

var imgData = document.querySelector('#img');
var imageArray = JSON.parse(imgData.dataset.list.replace(/'/g, '"'));

console.log(imageArray);
<img id="img" data-list="['photo2.jpg', 'photo3.jpg', 'photo4.jpg']" src="photo1.jpg">

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

The functionality of keydown is not functioning properly in the Chrome browser

Hey there, I've been working on some scripts and testing them in Firefox where they're running smoothly. However, when I tried testing them in Chrome, the keydown event doesn't seem to be working. I also attempted the keyup event with no suc ...

Strategies for managing large numbers within WebGL GLSL shader programs

What is the best approach to handle large numbers like the one provided in GLSL? I have a shader that requires Date.now() as a uniform, which is defined as: The Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 ...

Top approach to locating an image's duplicate on a server and retrieving its file path

My current project involves developing a web application specifically for managing digital assets, focusing solely on image files. Upon uploading an image, the file is stored in a designated folder and a corresponding row is added to a MySQL database with ...

Tips for modifying multiple divs with the same class using querySelector

I am curious about how to change the class on multiple divs at once using JavaScript. In the example below, only the first use of the class is recognized, while all subsequent ones are ignored. querySelectorAll does not seem to work. Thank you in advan ...

Troubles encountered during the installation of Visual Web Developer 2010?

Here is the situation I'm facing: After encountering some issues with PHP while working on an ASP.net project, I decided to reinstall everything. The installation of Apache, MySQL, and PHP went smoothly, but now I seem to be facing some problems. I ...

What is the best method to retrieve information from a nested JSON array?

Whenever a user submits data, I receive it in a nested JSON array format and I must extract that information. For example, the data could range from question_1 to question_5 in one submission, and then from question_1 to question_9 in another submission. ...

Authentication error: The API data retrieval was disrupted due to an unexpected termination of input

I encountered an error while trying to fetch data from an API using JavaScript. <button onclick="event.preventDefault(); getOdds()">Print odds</button> JS function getOdds() { const sportsKey = prompt("Enter the sports key:&q ...

Efficient arrow function usage in jQuery map functionality

Looking to implement an arrow function in jQuery's map function. However, after trying the following code snippet, titlesText ends up being the correct length but with empty strings: let titles = $(panelBody).find('h4'); let titlesText = $(t ...

Is it possible for bots to mimic onTouch events?

Query: In order to safeguard a mobile website from SPAM/Bots without resorting to user-unfriendly CAPTCHA, we are considering disabling onClick events at the server side while still permitting onTouch events. Can bots emulate the onTouch function, thus e ...

converting an angular object into a string representation

I stumbled upon this guide: . and it includes the following piece of code: import { Component } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl ...

Accessing API using Next.js 14

I am facing an issue with the following code which is written in next.js. The error displayed on the console is: GET http://localhost:3000/products/porducts.json 404 (not found) Additionally, I'm encountering this error: Uncaught (in promise) SyntaxE ...

Sped up object outpacing the mouse pointer

I'm currently developing a drag and drop minigame, but I've encountered an issue with the touch functionality. The draggable function (using only cursor) works flawlessly, however, when I tried to implement touch support for mobile and tablet use ...

Using the && operator for conditional rendering in a React return statement

How should I format my return statement in a class component when using the && operator in the condition like this: if (x === null && y === null) If the condition is met, display this HTML: <div className="col-12"> <SomeComponent /> < ...

Tool designed to analyze the timing of sub requests and methods in Node for benchmarking purposes

For my benchmarking and load testing needs, I initially utilized tools such as Apache Bench, Siege, and benchmark.js. However, these tools only provided me with the overall result or time taken from start to finish of the test. I am now seeking a tool or l ...

Submit numerous queries to verify the presence of a name and assign it to the name attribute

I have a collection of unique devices. As part of a process, I need to assign a default name to each device ("DeviceX" - where X is a sequential number), but some of the names may already be in use. To handle this, I must make a request to check ...

When attempting to declare a functional component in React utilizing styled-components in TypeScript, an error is encountered stating "No overload matches this call."

Playground https://codesandbox.io/s/typescript-type-checking-question-0b42t Sample Code type BadgeTypes = { success: string; secondary: string; alert: string; text: string; }; type Theme = { fonts?: object; borderRadius: string; primary?: o ...

Learn how to bind a click event to a directive in AngularJS

Hello there! I am a beginner in AngularJS and I have a situation where I need to change the background color of a div with the ID "#single" and then make a call to the back-end server on a click event. Unfortunately, I am unsure how to achieve this using a ...

Adding text chips to a text field in Vuetify - A simple guide

I have successfully integrated a text field with vuetify and now I am looking to incorporate chips into it. Currently, chips are only added if the entered text matches a specific pattern (such as starting with '{' and ending with '}'). ...

unable to use redirect feature for specific URLs with nodejs module

I have been using the request nodejs module to retrieve HTML content from websites. However, I have encountered issues with certain redirection websites, as shown below: var request = require('request'); var options = { url: "http://www.amw ...

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 ...