Rajesh Upadhayaya
Rajesh Upadhayaya

Reputation: 81

Cannot read property 'body' of null, in chrome but working in firefox

I am trying to get data from a <object> tag using JavaScript. But while reading I get the below error in Chrome:

Cannot read property 'body' of null

But the same code is working fine in Firefox. Below is my code:

<body onload="init()">
    <object id="data" data="graph.json" type="text/plain" style="display:none"></object>
</body>
<script>
var init = function(){
    var json = document.getElementById("data").contentDocument.body.childNodes[0].innerHTML;
    var graph = JSON.parse(json);
}
</script>

So document.getElementById("data").contentDocument.body.childNodes[0].innerHTML gives the error.

Upvotes: 0

Views: 2741

Answers (2)

trincot
trincot

Reputation: 351128

Instead of .contentDocument, you could use .contentWindow.document, which seems to work on Chrome.

Also, I would not use .childNodes[0].innerHTML, but .textContent, because HTML may include HTML entities (like &gt; when your JSON has < somewhere), while textContent will just give the plain text.

So:

document.getElementById("data").contentWindow.document.body.textContent

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85593

You may simply use innerHTML:

document.getElementById("data").innerHTML

The <object /> element will hold the html when you define source - the browser will render the html in it. So, innerHTML simply will work and you don't need to worry about contentDocument and or contentWindow. You needed this if you were using iframe.

Upvotes: 1

Related Questions