I am trying out localStorage and attempting at getting text from a div and storing it in localStorage, however, it sets it as an [object Object] and returns [object Object]. Why is this happening?
localStorage.content = $('#test').html('Test');
$('#test').html(localStorage.content);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>
The
localStorage
can only store string content and you are trying to store a jQuery object sincehtml(htmlString)
returns a jQuery object.You need to set the string content instead of an object. And use the
setItem
method to add data andgetItem
to get data.Use
setItem
andgetItem
if you want to write simple strings to localStorage. Also you should be usingtext()
if it's the text you're after as you say, else you will get the full HTML as a string.Sample using .text()
JSFiddle: https://jsfiddle.net/f3zLa3zc/
Storing the HTML itself
JSFiddle:
https://jsfiddle.net/psfL82q3/1/
Update on user comment
A user want to update the localStorage when the div's content changes. Since it's unclear how the div contents changes (ajax, other method?)
contenteditable
andblur()
is used to change the contents of the div and overwrite the oldlocalStorage
entry.If we were using ajax we would instead trigger the function it via the function responsible for updating the contents.
JSFiddle:
https://jsfiddle.net/g1b8m1fc/
You said you are attempting to get the text from a div and store it on local storage.
Please Note: Text and Html are different. In the question you mentioned text.
html()
will return Html content like<a>example</a>
. if you want to get Text content then you have to usetext()
instead ofhtml()
then the result will beexample
instead of<a>example<a>
. Anyway, I am using your terminology let it be Text.Step 1: get the text from div.
what you did is not get the text from div but set the text to a div.
is actually setting text to div and the output will be a jQuery object. That is why it sets it as
[object Object]
.To get the text you have to write like this
$('#test').html();
This will return a string not an object so the result will be
Test
in your case.Step 2: set it to local storage.
Your approach is correct and you can write it as
But the preferred approach is
localStorage.setItem(key,value);
to setlocalStorage.getItem(key);
to get.key and value must be strings.
so in your context code will become
But I don't find any meaning in your code. Because you want to get the text from div and store it on local storage. And again you are reading the same from local storage and set to div. just like
a=10; b=a; a=b;
If you are facing any other problems please update your question accordingly.