0

I'm trying to make a div element in JavaScript and place a google chart on it.

google.setOnLoadCallback(drawChart)

function drawChart() {
div = document.createElement('div');
div.id = 1;
div.style.position = 'absolute';
div.style.top = 291;
div.style.left = 439;
div.style.width = 500;
div.style.height = 500;
document.body.appendChild(div);
var data = google.visualization.arrayToDataTable([
 ['Task', 'Hours per Day'],
 ['Work',     1],
 ['Eat',      2],
 ['Commute',  2],
 ['Watch TV', 2],
 ['Sleep',    2]
]);
var options = {'title':'How Much Pizza I Ate Last Night',
 'width':300,
 'height':300};
var pieChart = new google.visualization.PieChart(document.getElementById(1));
pieChart.draw(data, options);
}

Nothing shows up... but if I manually make a div in body with <div> tag... and give its id here, that works. Am I doing something wrong with new div creation or what?

1
  • Should this google.setOnLoadCallback(drawChart) not be after the function being defined? ie in the end of that script? Commented Dec 7, 2013 at 20:58

1 Answer 1

2

ID's are strings, change

div.id = 1;

to

div.id = 'MyElement';

and

var pieChart = new google.visualization.PieChart(document.getElementById('MyElement'));

or just use the reference from the variable

var pieChart = new google.visualization.PieChart(div);

and so are styles btw :

div.style.top = '291px';
Sign up to request clarification or add additional context in comments.

4 Comments

Already done both.. still nothing shows up. and who said ids are string?? they can be integers too.
Using an integer would probably work in most browsers, but no, ID's are strings, but in HTML5 they can start with a number, but it's still a string, so the proper way would be element.id = '1'; note the quotes.
@AbdulJabbar: <div id=1></div> --> var x = document.getElementById(1); --> console.log(typeof x.id); === string --> fiddle
And yes, setting any style in plain JS is also done with strings, so it is required that you use a string and the unit, as in '444px'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.