user4435243
user4435243

Reputation:

May I store array inside a html element and than use it as an array again

I have to store array in html element, so I can use it later.

I want to get --> arrayFromHtml[0] as [0,1] --> arrayFromHtml[1] as [1,2]

<p id="demo"></p>

<script>
  var array = [
    [0, 1],
    [1, 2],
    [1, 2]
  ];
  document.getElementById("demo").innerHTML = array;

  // than in another code block, i want to use array as

  var useStoredArray = function(arrayFromHtml) {
    console.log(arrayFromHtml[0]);
  }
  useStoredArray(document.getElementById("demo").innerHTML);
</script>

Upvotes: 0

Views: 105

Answers (2)

Mamun
Mamun

Reputation: 68933

You should store the stringified array, then parse the array to retrieved items. Also, instead of innerHTML I will suggest you to use innerText or textContent when get/set plain text (not htmlString):

<p id="demo"></p>

<script>
  var array = JSON.stringify([[0,1], [1,2], [1,2]]);
  document.getElementById("demo").textContent = array;

  var useStoredArray = function(arrayFromHtml){ 
    console.log(JSON.parse(arrayFromHtml)[0]);
  }
  useStoredArray(document.getElementById("demo").textContent);
</script>

Upvotes: 2

mplungjan
mplungjan

Reputation: 178421

Not like that

You can use JSON.stringify and data attributes

That is assuming you WANT to show 0,1,1,2,1,2 but want to store [[0,1],[1,2],[1,2]]

<p id="demo"></p>

<script>
  var array = [
    [0, 1],
    [1, 2],
    [1, 2]
  ];
  document.getElementById("demo").innerHTML = array;
  document.getElementById("demo").dataset.storedarr = JSON.stringify(array);
  // than in another code block, i want to use array as

  var useStoredArray = function(obj) {
    const arrayFromHTML = JSON.parse(obj.dataset.storedarr);
    console.log(arrayFromHTML[0]);
  }
  useStoredArray(document.getElementById("demo"));
</script>

Upvotes: 3

Related Questions