how to make the localStorage so that the currents <p> Did the JavaScript disappear after reloading?</p>
-
js
function fuf() { let ghj = document.querySelector('body'); ghj.innerHTML += "<p>приветик</p>"; }
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width"> <title>Document</title> </head> <body onload="fyf()"> <button onclick="fuf()">кликЕР</button> <p id="loshok"></p> <script src="code.js"></script> </body> </html>
-
In your version, it's gonna be tough:
Keep it like that. ♪ ♪
localStorage.setItem("saved", JSON.stringify([...document.querySelectorAll("body p")] .map(el => el.innerText) ) );
Read it like that. ♪ ♪
let savedParagraphs = JSON.parse(localStorage.getItem("saved")) || []; savedParagraphs.forEach(text => { let newElement = document.createElement("p"); newElement.innerText = text; document.body.appendChild(newElement); });
What a joke... In localStorage, you can only keep lines! So the mass should be retained as JSON and read as JSON. If you can't read it, it's null. JSON.parse(null) will be null and if the result null then
null или пустой_массив
♪|| []
He'll return the empty space. Then we go round (if there was) every element in the words and create a paragraph--ghj.innerHTML += "<p>приветик</p>"
That it is not right in the root, but correctly through the creation of the DOM element of the paragraph and the setting of text meaning. Then we add a new, created element to the BODY tagu.document.body