Cannot read the appendChild property from null and other null variables

Before I get started, I just want to let you know that I'm new to web development. I also want to keep this 100% javascript, so there is no jquery or other languages ​​on it.

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

The error I am getting is the following:

Uncaught TypeError: Cannot read the 'appendChild' property from null on drawBarChart (script.js: 58) with script.js: 66

This is 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 do not work due to the same error:

Uncaught TypeError: cannot read the 'scrollWidth' property from null on drawBarChart (script.js: 42) with script.js: 66

or

Uncaught TypeError: 'scrollHeight' null      drawBarChart (script.js: 44)      script.js: 66

appendChild, , , , , , , . HTML- - div, :

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

, , , , . , .

+4
1

DOM, .

JS , DOM , , div .

jsbin.

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

+4

Source: https://habr.com/ru/post/1669650/


All Articles