Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
16
rated 0 times [  18] [ 2]  / answers: 1 / hits: 180467  / 8 Years ago, thu, november 24, 2016, 12:00:00

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>




More From » jquery

 Answers
13

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 use text() instead of html() then the result will be example 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.


$('#test').html("Test"); 

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


localStorage.key=value

But the preferred approach is


localStorage.setItem(key,value); to set


localStorage.getItem(key); to get.


key and value must be strings.


so in your context code will become


$('#test').html("Test");
localStorage.content = $('#test').html();
$('#test').html(localStorage.content);

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.


[#59929] Tuesday, November 22, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bobbidayanam

Total Points: 82
Total Questions: 99
Total Answers: 96

Location: Venezuela
Member since Sat, Apr 24, 2021
3 Years ago
;