anvaka / VivaGraphJS

Graph drawing library for JavaScript
Other
3.73k stars 423 forks source link

Cannot read property 'appendChild' of null - sample usage #221

Closed robert-skarzycki closed 6 years ago

robert-skarzycki commented 6 years ago

Hi,

I'm trying to play with vivagraphjs, but when I'm using the simple sample from the README, I'm getting following error (I use Chrome):

Uncaught TypeError: Cannot read property 'appendChild' of null
    at Object.init (vivagraph.min.js:2)
    at N (vivagraph.min.js:2)
    at Object.run (vivagraph.min.js:2)
    at graph.js:10

Could you help me with this? Please take a look on the piece of code here: https://github.com/robert-skarzycki/js-graph-experiment/tree/plain-js

P.S. I'm getting same error regardless if I use basic "use case" when chart should be automatically appended to the document or when I'm passing handler to the container (the commented code in the linked source above).

anvaka commented 6 years ago

You need to load your javascript after the body is rendered. This should fix it:

<!DOCTYPE html>
<html>

<head>
    <script type="text/javascript" src="vivagraph.min.js"></script>
    <style>
        .graph {
            border: 1px solid red;
            width: 500px;
            height: 500px;
        }
        svg {
            width: 100%;
            height: 100%;
        }
    </style>
</head>

<body>
    <h1>Graph</h1>
    <p>graf</p>
    <div class="graph" id="graph-container"></div>
    <script type="text/javascript" src="graph.js"></script>
</body>

</html>

I've added svg style to take the entire container, and I'm using your commented graph.js:

var graph = Viva.Graph.graph();
graph.addLink(1, 2);

var renderer = Viva.Graph.View.renderer(graph, {
    container: document.getElementById('graph-container')
});
renderer.run();
robert-skarzycki commented 6 years ago

Thanks, it helped!

Petercopter commented 5 years ago

Totally random, but I had this same problem with react-hotloader when I upgraded my packages. I moved my javascript include from the head to the bottom of the page, and that did the trick.

Hope this helps anyone else Googling Cannot read property 'appendChild' of null

mohsinrahman commented 4 years ago

Moving javascript include at bottom does not work for all cases.