Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 localStorage replace data to already existing key

Tags:

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.

like image 520
Mircea Avatar asked Sep 20 '10 11:09

Mircea


People also ask

How do I replace items in localStorage?

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 .

How do I change localStorage key value?

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 .

How can I store multiple values in localStorage with same key?

Here it is simple what have created. var value = "aa" localStorage. setItem("testKey", value); var test = localStorage. getItem("testKey"); alert(test);

Can you modify localStorage?

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.


1 Answers

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().

like image 88
epascarello Avatar answered Sep 21 '22 05:09

epascarello