How to add item to local storage

  • A+

I am creating a song book app with 'add to favorite' button. i have song1.html song2.html and favorite.html.

in song1.html, when add to favorite button is clicked. i am storing the link to that song in local storage.

This is my song1.html

<!DOCTYPE html> <html> <body>    <button onclick="mySongOne()">add to favorite</button>      <script> function mySongOne() {   localStorage.setItem("favsong", "<a href=''><h1>song1</h1></a>"); }   </script>  </body> </html>

in song2.html, when add to favorite button is clicked. i am storing the link of the second song in local storage.


<!DOCTYPE html> <html> <body>    <button onclick="mySongTwo()">add to favorite</button>    <script> function mySongTwo() {   localStorage.setItem("favsong", "<a href=''><h1>song2</h1></a>"); }   </script>  </body> </html>

now i have a favorite.html for listing my favourite songs. and favourite.html will retrieve the links that i stored in local storage.


<!DOCTYPE html> <html> <body onload="myFunction()">  <div id="result"></div>    <script> function myFunction() {   document.getElementById("result").innerHTML = localStorage.getItem("favsong"); }  </script>  </body> </html>

Now i want to show both song 1 and song 2 in favorite.html. but only song 2 is displayed in favourite.html. How to accomplish this.


If you really need to append data to the same LocalStorage key, there is no built-in append function.

However, you can use a custom function, for instance the one proposed in this answer:, and get the following code to do what you want:

<!DOCTYPE html> <html> <body>  <div id="result"></div>  <script> // Check browser support if (typeof(Storage) !== "undefined") {     // Store     localStorage.setItem("list", "<h1>John<h1>");     appendToStorage("list", "<h2>David<h2>");      // Retrieve     document.getElementById("result").innerHTML = localStorage.getItem("list"); } else {     document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage..."; }  function appendToStorage(name, data){     var old = localStorage.getItem(name);     if(old === null) old = "";     localStorage.setItem(name, old + data); } </script>  </body> </html>


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: