I want to create a div after a click and store the created div in localStorage
.
b.addEventListener('click', addDiv);
function addDiv() {
var div = document.createElement('div');
}
CodePudding user response:
From the above comments ...
"@AlvéMonke ... almost correct. The OP needs to write a serializer which describes how an html element gets created e.g. by writing a JSON serializable data format. The JSON stringified value of this format then can be stored into and retrieved from the storage. The restored/parsed data format then can be send to a deserializer (needs to be written too) which upon the data does create an appropriate html element." – Peter Seliger
"@PeterSeliger can you please code your answer?"" – user16846263
A poor man's approach, though reliable, would be the usage of Element.outerHTML
for serializing (storing) together with the more advanced DOMParser.parseFromString
for deserializing (retrieving / parsing).
function putSerializedElementIntoStorage(storage, key, elmNode) {
// serialization.
const value = elmNode?.outerHTML ?? '';
// storage.
storage.setItem(key, value);
}
function getParsedElementFromStorage(storage, key) {
return (new DOMParser())
// deserialization ...
.parseFromString(
// ... from storage.
storage.getItem(key) ?? '',
"text/html",
)
.body
// parsed element.
.firstElementChild;
}
document
.querySelector('#save-element-markup')
.addEventListener('click', ({ currentTarget }) =>
putSerializedElementIntoStorage(
mock.localStorage,
currentTarget.id,
currentTarget,
)
);
document
.querySelector('#watch-stored-markup')
.addEventListener('click', ({ currentTarget }) =>
console.log({
storedMarkup: mock
.localStorage
.getItem(currentTarget.dataset.storageKey),
})
);
document
.querySelector('#append-parsed-element')
.addEventListener('click', ({ currentTarget }) => {
const elmNode = getParsedElementFromStorage(
mock.localStorage,
currentTarget.dataset.storageKey,
);
if (elmNode) {
document
.body
.appendChild(elmNode);
}
});
button { display: block; margin: 3px 10px; }
button:nth-child(1) { margin: 0 15px 12px;}
button:nth-child(2), button:nth-child(3) { margin: 6px 15px; }
hr { position: relative; left: -25%; width: 48%; }
.as-console-wrapper { left: auto!important; width: 50%; min-height: 100%; }
<button id="save-element-markup">
<em>save</em>
my markup
</button>
<button
id="watch-stored-markup"
data-storage-key="save-element-markup"
>
<em>watch</em> stored markup
</button>
<button
id="append-parsed-element"
data-storage-key="save-element-markup"
>
<em>append</em>
element, parsed from saved markup
</button>
<hr/>
<script>
// mock for the SO specific stack snippet
// due to the policies and environment are
// not allowing an original storage access.
const mock = {
localStorage: (function () {
// https://developer.mozilla.org/en-US/docs/Web/API/Storage
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
const storage = new Map;
function key(int) {
return [
...storage.keys()
][parseInt(int, 10)];
}
function setItem(key, value) {
return storage.set(String(key), String(value));
}
function getItem(key) {
return storage.get(String(key));
}
function removeItem(key) {
return storage.delete(String(key));
}
function clear() {
return storage.clear();
}
return {
get length() {
return storage.size;
},
key,
getItem,
setItem,
removeItem,
clear,
};
}()),
}
</script>
CodePudding user response:
b.addEventListener('click', addDiv);
function addDiv() {
var div = document.createElement('div');
localStorage.setItem("contentDiv",div);
}
To Retrieve can use like:
function getStoaregeDate(){
document.getElementById("elementId").innerHTML =
localStorage.getItem("contentDiv");
}
Hope this help. Thanks!