javascripthtmllocal-storagedisplaytagremove-if

Javascript - localStorage issues


In the script below, I want to be able to display on the main html page lists of paragraphs saved in the localstorage. In the html I defined an are with the id "content". I want to display the texte stored in the localstorage in this area.

In the script below the function "displaylocalstorage" does not allow me to display the values that have been saved in the localstorage with the function "storedparagraphs". Can you please give me some guidelines to correct the "displaylocalstorage" function? Is my while loop correct ? Is the way I call the fucntion "display locastorage" is correct ?

Here is the html and js script below:

Javascript:

const mybutton = document.getElementById ("addbutton");
const mytext = document.getElementById("mytext");
const content = document.getElementById("content");  

function displaylocalstorage() {
let n = 0;
while (localStorage.getItem("content" + n)) {
    n++;
}
while (n){
    const paragraph = document.createElement("p");
    paragraph.innerText = localStorage.getItem("content");
    content.appendChild(paragraph);
    n++
}

}

}

displaylocalstorage()

Solution

  • displaylocalstorage is not being called.

    add this to your js

    const buttonshow = document.getElementById("buttonshow");
    
    buttonshow.addEventListener("click", displaylocalstorage);
    

    and to your html:

     <input
            type="button"
            value="show"
            id="buttonshow"
            class="buttonshowall"
    />
    

    and console log items in the displaylocalstorage

    Thank would be a good start. Other than this in that paragraph remove length from n as n is a number. If you keep it as length it will error.

     if(n>0){
            let lastposition = n -1;
            localStorage.removeItem("content", lastposition)
        }
    

    Another big one is change const n to let as you try to update n and const won't allow you to do that.