How to clear localStorage on button click
I followed a tutorial on Youtube about localStorage and everything went fine. After that I tried to mess around with the concepts and wanted to add a button to remove the localStorage (id ="btnClear").
by UtmostCreator
November 05, 2021
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>How to clear localStorage on button click</title>
</head>
<body>
<content>
<fieldset>
<legend>Insert Data</legend>
<input type="text" id="inpKey" placeholder="Insert Key.." />
<input type="text" id="inpValue" placeholder="Insert Value.." />
<button type="button" id="btnInsert">Insert</button>
</fieldset>
<fieldset>
<legend>Local Storage</legend>
<ul id="outputList"></ul>
<br />
<button type="button" id="btnClear">Clear</button>
</fieldset>
</content>
<script type="text/javascript">
const printLSContent = function (el) {
for (let i = 0; i < localStorage.length; i++) {
let key = localStorage.key(i);
let value = localStorage.getItem(key);
let li = document.createElement('li');
li.innerHTML = `K: ${key}; V: ${value}`;
el.appendChild(li);
}
}
document.addEventListener("DOMContentLoaded", function (event) {
const inpKey = document.getElementById("inpKey");
const inpValue = document.getElementById("inpValue");
const btnInsert = document.getElementById("btnInsert");
const outputList = document.getElementById("outputList");
const btnClear = document.getElementById("btnClear");
// element.addEventListener(event, handler[, options]); // type - event type; listener - event handler; options -
btnInsert.addEventListener('click', function () {
const key = inpKey.value;
const value = inpValue.value;
localStorage.setItem(key, value);
location.reload();
}, false);
printLSContent(outputList);
// //BUTTON CLEAR
btnClear.addEventListener('click',...