Javascript Browser Storage key() Method loop through each local storage item

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>
<button onclick="displayItems()">Display items</button>
<p id="demo"></p>

<script>
function createItems() {//from  w w w. j av a  2  s . c  o  m
  localStorage.setItem("mytime", Date.now());
  localStorage.setItem("myname", "CSS");
  localStorage.setItem("myage", 36);
}

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