d3.select("#element") not working when code above the html element

Rick Jolly picture Rick Jolly · May 29, 2013 · Viewed 144.2k times · Source

This works:

<div id="chart"></div>
<script>var svg = d3.select("#chart").append("svg:svg");</script>

This doesn't:

<script>var svg = d3.select("#chart").append("svg:svg");</script>
<div id="chart"></div>

I tried wrapping the code in a jquery document.ready(), grabbing the element with jquery, and passing it into d3.select, but that didn't work either. Edit Once I got the jquery document.ready() syntax right, it worked.

Any way I can include the javascript at the top of the page and still select an element below? Thanks.

Answer

Micah picture Micah · May 29, 2013
<script>$(function(){var svg = d3.select("#chart").append("svg:svg");});</script>
<div id="chart"></div>

In other words, it's not happening because you can't query against something that doesn't exist yet-- so just do it after the page loads (here via jquery).

Btw, its recommended that you place your JS files before the close of your body tag.