1

I am trying to use the DOM method to display a JSON object that I created inside of my .js file, and I need to display it in the HTML page. This is what my code looks like and it is not working.

function JSONMethod(){
    carInfo = {"make":"BMW", "model":"M5","mear":"2017","color":"Black"};
    myJSON = JSON.stringify(carInfo);
    localStorage.setItem("theJSON", myJSON);

    text = localStorage.getItem("theJSON");
    obj = JSON.parse(text);

    for(var i = 0; i < obj.length; i++)
    {
        var para = document.createElement("li");
        var node = document.createTextNode(obj[i]);
        para.appendChild(node);
        var element = $("display");
        element.appendChild(para);
    }
}

The $ function is this

function $(theId){
    return window.document.getElementById(theId);
}
Programmer
  • 105
  • 2
  • 11
  • 1
    1) You probably meant `$('#display)` or some other **valid** selector. 2) Objects don't have a `length` property. Try a [`for..in` loop](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...in). 3) All that local storage stuff is completely superfluous to your question – Phil Mar 07 '17 at 03:25
  • I have actually been using just $("display") the entire time, and it seems to be working. I keep seeing around on comments people saying to add the "#". Why so? the $ function just returns the window.document.getElementById(theId) – Programmer Mar 07 '17 at 03:49
  • My apologies, I assumed you were using jQuery. I wouldn't recommend relying on `$` being defined. Seems like something only Chrome and Firefox do ~ http://stackoverflow.com/questions/22244823/what-is-the-dollar-sign-in-javascript-if-not-jquery – Phil Mar 07 '17 at 03:58
  • No worries, I should clarify what the $ function is. Thank you though! – Programmer Mar 07 '17 at 04:11

1 Answers1

1

I'm not sure why exactly you are saving to and then reading from localStorage, or stringifying and then reparsing your object. Most of the code you gave above can be removed or reduced in size drastically using constructs like .textContent and Array#forEach.

Your underlying problem, however, is that you cannot iterate over regular objects using a for-loop and an index. You have to use a function like the built-in Object.keys to get all of its properties and then do something with them.

function JSONMethod (carInfo) {

  Object.keys(carInfo).forEach(function (k) {
    var li = document.createElement("li")
    li.textContent = k + ': ' + carInfo[k]
    this.appendChild(li)
  }, document.getElementById('display'))

}

JSONMethod({
  "make": "BMW",
  "model": "M5",
  "mear": "2017",
  "color": "Black"
})
<ul id="display"></ul>
gyre
  • 16,369
  • 3
  • 37
  • 47
  • Ohhhh ok ok yeah the storing thing I got from the w2schools.com. And the storing isn't necessary now that I realized and found other links. I will try to rearrange my code with your answer and see if it work! Thanks! – Programmer Mar 07 '17 at 03:40