0

Can anyone explain to me why the code below gives (object, Object)?
(the console.log(dope) gives what it should but after JSON.stringify and JSON.parse it just says object,Object ). If you could tell me why it's doing that it would be great.

var nombrememes = document.getElementsByClassName("meme").length;
var memenumber = nombrememes + 1;

var newmeme = prompt('Please paste the link of the meme below!');
memes.push ('placememe'+memenumber+'');

var div = document.createElement('div');
document.body.appendChild(div);
div.id = 'placememe'+memenumber+'';
div.className = 'meme';
div.innerHTML = '<img src="'+newmeme+'" width="700" height="700" alt="" />';


var dope = document.getElementById('placememe'+memenumber+'');
console.log(dope);
localStorage.setItem('dope', JSON.stringify(dope));
var pla = JSON.parse(localStorage.getItem('dope'));
alert(pla);
DrBad
  • 1
  • 1
  • 2

3 Answers3

1

This is because after JSON.parse you are now dealing with a JavaScript Object.

IE when you're doing {}.toString() you won't get back '{}' you get back [object Object] which is what Javascript returns for a string representation of an object. This is why JSON.stringify() is necessary to convert a Javascript Object to JSON.

If you want to get the string for your alert simply just leave the value coming out of localStorage as the string representation.

var pla = localStorage.getItem('dope');
alert(pla);
peteb
  • 18,552
  • 9
  • 50
  • 62
0

This won't work. See this question. You're trying to serialize a DOM node into JSON, but that's not possible. Instead, it serializes as an empty object. Which you are then trying to alert(...). When you alert an object, it will contain [Object object] every time.

The JSON.stringify/JSON.parse operations aren't really related to your issue. It'll work just fine with any valid object - just not a DOM node.

To save parts of the DOM node, you can save individual scalar properties. For example, the innerHtml can be saved. Add other properties as desired.

var o = {
    inner: dope.innerHtml
};
  • Ok thanks, now I understand why it cant work. But can you explain to me how can I change my DOM node to an object, so that it may work. – DrBad Feb 11 '17 at 01:37
0

Suggestion :

If you want to print the object for debugging the code, try this :

console.log(pla)

Otherwise try this in case of alert :

Try this it will give you output with indented JSON object :

alert(JSON.stringify(pla, null, 4));

Benefits :

  • cross-platform support
  • Standardized in ECMAScript 5th Edition
  • support in Firefox , Chrome , Safari, and IE8.
Debug Diva
  • 26,058
  • 13
  • 70
  • 123