jmj
jmj

Reputation: 145

session storage is not working properly

I have tried for session storage functionality in javascript. I stored a dynamic data in old.html file & tried to retrieve it in new.html webpage. The getItem returns "null" in new.html page.

My old.html file has;

<script>
var name=document.createTextNode("All the Best");
sessionStorage.setItem("data",name);</script>

And new.html file has;

<script>
var newdata=sessionStorage.getItem('data');
alert(newdata); </script>

Upvotes: 3

Views: 16188

Answers (2)

Zale
Zale

Reputation: 65

As Dark Falcon said, web (or session) storage can only store String values. You could try to store the string representation of the dom element(maybe with innerHTML) you want to save.

var data = document.getElementById("test").innerHTML;
sessionStorage.setItem("data", data);

and later on retrive it in the other file:

var newdata=sessionStorage.getItem('data');
document.getElementById("anotherfileID").innerHTML = newdata;

Although, I dont think passing one DOM element from one HTML file to another is the best thing to do. what are you trying to do ?

Upvotes: 1

Dark Falcon
Dark Falcon

Reputation: 44181

Session storage stores strings, not DOM nodes. Store the string directly:

<script>
sessionStorage.setItem("data", "All the Best");
</script>

<script>
var newdata=sessionStorage.getItem('data');
alert(newdata);
</script>

Upvotes: 6

Related Questions