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); } 
4
  • 1
    1) You probably meant $('#display) or some other valid selector. 2) Objects don't have a length property. Try a for..in loop. 3) All that local storage stuff is completely superfluous to your question Commented Mar 7, 2017 at 3: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) Commented Mar 7, 2017 at 3: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 ~ stackoverflow.com/questions/22244823/… Commented Mar 7, 2017 at 3:58
  • No worries, I should clarify what the $ function is. Thank you though! Commented Mar 7, 2017 at 4:11

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.