How to store array in HTML data-attribute?

Last Updated on Mar 26, 2024

Array stored in data-attribute and used by JavaScript

In HTML data-attributes, you can store strings and numbers, and if you need, you can also store an array in them.

In fact, you can also store any JSON object. Hence, this tutorial can also be applied to JSON objects.

  1. Store array in HTML data-attribute

    Store the array or JSON in the correct format ([0, 1, 2]) in the data-attribute.

    Array of numbers
    <p data-sample="[0, 1, 2]"></p>
    
    Array of strings
    <p data-sample='["one", "two", "three"]'></p>
    

    If it's coming from a backend server, you need to convert it first to a JSON-encoded string, like using the json_encode function in PHP.

    <p data-sample="<?= json_encode($result); ?>"></p>
    
  2. Restore the array using JSON.parse in JavaScript

    The JSON.parse method in JavaScript converts the JSON-encoded string into a JavaScript object. However, if the string is in array format, it will return a JavaScript array. Therefore, you can use this to restore your array, if it's an array, or JSON, if it's JSON.

    let element = document.querySelector("[data-sample]");
    data = JSON.parse(element.dataset.sample);
    

Conclusion

To store an array or JSON in an HTML data-attribute, you need to store it in an array or JSON-encoded string. Then, using the JSON.parse method in JavaScript, you can return it back to an array or JSON.

© John Michael Balbarona