I have the following localStorage key:
localStorage.setItem(1, "<div id='MyId'>value 1</div><div id='NewId'>other value</div>");
Is it possible to replace, change only the second id, make the:
<div id='MyId'>value 1</div><div id='NewId'>other value</div>
turn into
<div id='MyId'>value 1</div><div id='NewId'>replaced value</div>
I do not want to delete this key and create a new one, just replace a part of it. Thank you.
To replace local storage data for an already existing key with JavaScript, we can get the value with getItem , change the returned value, and then save it with setItem . We call setItem with the key and value to add an entry with key string and value 'foo' . Then we get the item with key string with getitem .
You can update a local storage variable by using localStorage. setItem(key, value) with your key and value. Make sure to update the value before calling localStorage. setItem .
Here it is simple what have created. var value = "aa" localStorage. setItem("testKey", value); var test = localStorage. getItem("testKey"); alert(test);
Local storage is bound to the domain, so in regular case the user cannot change it on any other domain or on localhost. It is also bound per user/browser, i.e. no third party has access to ones local storage.
Taken from Dive into HTML5:
Calling setItem() with a named key that already exists will silently overwrite the previous value.
So read the value with getItem() [if needed], do your replace, set the new value with setItem().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With