Javascript Challenge #10: LocalStorage API

This is another challenge in Javascript where you have to make use of LocalStorage api. Please do checkout my previous video about localStorage to learn more about it.

window.addEventListener('load', showAll);

function setStorage(){
    const name = document.querySelector('#name').value;
    const age = document.querySelector('#age').value;
    localStorage.setItem(name, age);
    showAll();
}

function showAll(){
    document.querySelector('ol').innerHTML = '';

    const keys = Object.keys(localStorage);

    keys.forEach(name =>{
        let element = document.createElement('li');

        let age = localStorage.getItem(name);
        let detail = document.createTextNode(`${name}: ${age}`);
        element.appendChild(detail);
        document.querySelector('ol').appendChild(element);
    });
}

function clearStorage(){
    localStorage.clear();
    showAll();
}

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>

<body>

    <div>
        <input type="text" placeholder="name" id="name">
        <input type="text" placeholder="age" id="age">
        <button onclick="setStorage()">ADD</button>
        <button onclick="clearStorage()">CLEAR</button>
    </div>

    <ol></ol>
     <script src="script.js"></script>
</body>

</html>

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •