Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'appendChild' of null and other null variables

Before I get started I just want to let you know I'm quite new to web development. I also want to keep this 100% javascript so no jquery or other languages for now.

The following code originates from this video: https://www.youtube.com/watch?v=esa5hJegRfI

The error I'm getting is the following:

Uncaught TypeError: Cannot read property 'appendChild' of null at drawBarChart (script.js:58) at script.js:66

This is the javascript:

var sampleData = [23,45,14,47,24,57,24,35];

function _div(id){
    return document.getElementById(id);
}

function drawBarChart(dataset, idOfContainer){

var chartContainer = _div(idOfContainer)

if(typeof(dataset) != "object"){
    return;
}

var heightOfContainer = chartContainer.scrollWidth;

var widthOfContainer = chartContainer.scrollHeight;

var widthOfBar = parseInt(widthOfContainer / dataset.length) - 2;

for(var i = 0; i < dataset.length; i++){

    var divElement = document.createElement("div");

    divElement.setAttribute("class", "div2");

    divElement.style.marginLeft = parseInt(i * 2 + i * widthOfBar) + "px";
    divElement.style.height = parseInt(dataset[i]) + "px";
    divElement.style.width = parseInt(widthOfBar) + "px";
    divElement.style.top = (heightOfContainer - parseInt(dataset[i]) - 1) + "px";
    chartContainer.appendChild(divElement);

}
return false;
}



drawBarChart(sampleData, "div1");



console.log();

The variables heightOfContainer and widthOfContainer don't work because of the same error:

Uncaught TypeError: Cannot read property 'scrollWidth' of null at drawBarChart (script.js:42) at script.js:66

or

Uncaught TypeError: Cannot read property 'scrollHeight' of null at drawBarChart (script.js:44) at script.js:66

The last appendChild function does not seem to work and I have looked at other issues similar to this but can't seem to find one. The associated HTML code is just a div but if you want it here it is:

<div id="div1" ></div>

I know this error is quite personal and won't affect many others but I have asked elsewhere for help and I couldn't find out why it didn't work. Hope you can help and thanks for your time.

like image 629
Gaetan Almela Avatar asked Feb 14 '17 01:02

Gaetan Almela


Video Answer


1 Answers

Your code is loaded before the DOM is ready, so the selectors can't find those elements on the page.

You can put your JS at the bottom of the page so the DOM is fully loaded before the code is run and in turn your div element is available to the selector.

Here is a jsbin.

http://jsbin.com/poqefopuyu/edit?html,output

like image 96
Mike Havrilla Avatar answered Sep 27 '22 22:09

Mike Havrilla