Javascript Browser Storage length Property for looping

Introduction

Loop through each local storage item and display the names:

This example demonstrates how to loop through all the local storage items for this domain.

View in separate window

<!DOCTYPE html>
<html>
<body>
<button onclick="createItems()">Create local storage items</button>
<h2>Display Items</h2>

<p>Click the button to display all items:</p>

<button onclick="displayItems()">Display items</button>

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

<script>
function createItems() {//from w  ww. j  a  v  a2  s. c o m
  localStorage.setItem("mytime", Date.now());
  localStorage.setItem("myname", "java2s.com");
  localStorage.setItem("myage", 42);
}

function displayItems() {
  var l, i;
  document.getElementById("demo").innerHTML = "";
  for (i = 0; i < localStorage.length; i++) {
     x = localStorage.key(i);
     document.getElementById("demo").innerHTML += x + "<br>";
  }
}
</script>

</body>
</html>



PreviousNext

Related