To store an array in local storage and then display it in the DOM using JavaScript, follow these steps:

Step 1: Store the Array in Local Storage To store the array in local storage, you need to convert it to a JSON string using JSON.stringify() and then use the localStorage.setItem() method to save it.

const myArray = ['apple', 'banana', 'orange']; const arrayString = JSON.stringify(myArray); localStorage.setItem('myArray', arrayString);

Step 2: Retrieve the Array from Local Storage To retrieve the array from local storage, use the localStorage.getItem() method and then parse the JSON string back to a JavaScript array using JSON.parse().

const arrayString = localStorage.getItem('myArray'); const myArray = JSON.parse(arrayString);

Step 3: Display the Array in the DOM Now that you have the array in your JavaScript code, you can display its contents in the DOM. There are various ways to do this, but one simple approach is to create an HTML element (e.g., a <ul> list) and add the array elements as list items.

<!DOCTYPE html> <html> <head> <title>Display Array in DOM</title> </head> <body> <ul id="arrayList"> <!-- List items will be added here --> </ul> <script> // Retrieve the array from local storage const arrayString = localStorage.getItem('myArray'); const myArray = JSON.parse(arrayString); // Get the DOM element where the array will be displayed const arrayListElement = document.getElementById('arrayList'); // Loop through the array and add list items to the DOM myArray.forEach(item => { const listItem = document.createElement('li'); listItem.textContent = item; arrayListElement.appendChild(listItem); }); </script> </body> </html>

In this example, the array stored in local storage is retrieved, and each element is added as a list item within the <ul> element with the ID arrayList.

When you open this HTML file in your browser, it will display the array elements in a list format.

Remember that local storage has limitations on the amount of data you can store (typically a few megabytes), so be mindful of the size of the array you are storing. If the array is too large, consider using alternative storage solutions like IndexedDB or a backend server.

Have questions or queries?
Get in Touch