1

The following script returns an error "cannot read property '1' of undefined", yet I can read the object in the Chrome console just fine. I have also tried obj[0].NodeName[1] which displays the value in the Chrome console but then the error says it cannot set property innerHTML of null".

What is the correct syntax to read the JSON elements into my HTML?

<script>
var nodeList='[{"NodeName":["Node1","Node2","Node3","Node4","Node5","Node6" ]}]';
obj = JSON.parse(nodeList);
document.getElementById("NodeName").innerHTML=obj.NodeName[1];
</script>   
NODE Name: <span id="NodeName"></span><br> 
Ja͢ck
  • 161,074
  • 33
  • 239
  • 294

4 Answers4

4

The script runs before the document has finished loading and the NodeName element doesn't exist in the document yet. Run your script in an onload event handler or move your script element after the span.

gilly3
  • 78,870
  • 23
  • 132
  • 169
0
<script>
var nodeList='[{"NodeName":["Node1","Node2","Node3","Node4","Node5","Node6" ]}]';
obj = JSON.parse(nodeList);
document.getElementById("NodeName").innerHTML=obj[0].NodeName[1];
</script>   

See this jsfiddle http://jsfiddle.net/sajith/n2xE9/

SajithNair
  • 3,821
  • 1
  • 15
  • 23
  • While not voted down, your answer did not solve my problem. It works fine in jsfiddle, but not on my webpage. I had already tried the exact same script as noted in the question. The problem was really due to the position of the span tag in reference to the script. – FlashSolutions Mar 03 '14 at 13:31
0

You add variable nodeList

var nodeList='[{"NodeName":["Node1","Node2","Node3","Node4","Node5","Node6" ]}]';

and then pars it to object.

obj = JSON.parse(nodeList);

So you should use:

document.getElementById("NodeName").innerHTML=obj[0].NodeName[1];
0

The solution was to place the span tag above the script like so...

NODE Name: <span id="NodeName"></span><br> 

<script>
var nodeList='[{"NodeName":["Node1","Node2","Node3","Node4","Node5","Node6" ]}]';
obj = JSON.parse(nodeList);
document.getElementById("NodeName").innerHTML=obj[0].NodeName[1];
</script>   

I had already tried using the above script syntax but moving the span tag before the script was what fixed the issue for me. Apparently this had already been answered in a previous post but I was unable to find it.

Thank you all for your help.