简体   繁体   中英

Cannot get innerHTML for JSON object

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> 

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.

<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/

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];

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM