0

I know how to use javascript arrays. But is there any way to get and set arrays from html data-attribute values ?

Look at this:

<div data-array="Apple, Banana, Jam, Strawberry, Peanut"></div>

Js Code:

<script> const fruits = [There will be the values or data from data-array attribute]; </script>

How can I do it using javascript or jquery ?

MrUpsidown
  • 21,592
  • 15
  • 77
  • 131
  • Duplicate of https://stackoverflow.com/questions/2858121/how-can-i-convert-a-comma-separated-string-to-an-array – MrUpsidown Dec 16 '22 at 13:13
  • Duplicate of https://stackoverflow.com/questions/96428/how-do-i-split-a-string-breaking-at-a-particular-character – MrUpsidown Dec 16 '22 at 13:14

2 Answers2

2

You need to grab the DOM element in JS somehow, e.g. by giving it an ID.

Then you can access the data attribute and split it into an array. Example:

const foods = document.querySelector("#foods");
const fruits = foods.dataset.array.split(", ");

console.log(fruits);
<div id="foods" data-array="Apple, Banana, Jam, Strawberry, Peanut"></div>
Adam Pearson
  • 304
  • 1
  • 7
  • 1
    In addition, you can directly grab an element with document.querySelector('[data-array]'), but if there are multiple elements with the same data attribute, it may be a good idea to give them unique IDs and grab them with their ID's. – Ugur Kellecioglu Dec 16 '22 at 12:56
  • @UgurKellecioglu or you could use `querySelectorAll('[data-array']')` and loop through them using `forEach()`. But, yeah, having some sort of unique `id` would certainly be helpful – disinfor Dec 16 '22 at 13:11
1

If you want to get the values for all the elements with data-array you can. However, if you're targeting one specific element attach an id/identifier and target it via that tag.

<div data-array="Apple, Banana, Jam, Strawberry, Peanut"></div>

<script>
    var data = document.querySelector('*[data-array]')?.getAttribute('data-array')
    const elems = data?.split(',')
    console.log(elems)
</script>
data?.split the ? in there allows the split to execute only if data is not undefined.