Reputation: 253
I try to assign an object for further handling with jQuery but it doesn't work. Here's my code:
$('.var').on('click', function () {
console.log($(this));
sessionStorage.setItem('object', JSON.stringify($(this)));
console.log(JSON.parse(sessionStorage.getItem('object')));
}
Both console logs don't have the same value. Why?
Second example:
$('.var').on('click', function () {
sessionStorage.setItem('object', JSON.stringify($(this)));
var item = JSON.parse(sessionStorage.getItem('object'));
item.addClass('not-work'); //does not work
$(this).addClass('work'); //works
e.preventDefault();
}
What am I doing wrong with sessionStorage().
Upvotes: 0
Views: 213
Reputation: 191976
JSON.stringify strips methods from the stringified object, because valid JSON does not include functions.
Example:
var obj = {
prop: 5,
method: function() {}
};
JSON.stringify(obj);
Result: "{"prop":5}"
Upvotes: 2
Reputation: 13734
@Ori Drori's answer explains the first example.
In the second example, you get the DOM element (jquery wrapped), convert it to a string!
and save in the sessionStorage.
And then get this string
out of sessionStorage, do JSON.parse
in hope of getting the DOM element, but instead you'll get a javascript object which is certainly not an element in the DOM tree (as I believe you're expecting) & hence, calling .addClass
on it doesn't work.
Upvotes: 0