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.
d3. select selects the first matching element whilst d3. selectAll selects all matching elements. Both functions take a string as its only argument. The string specifies which elements to select and is in the form of a CSS selector string (e.g. div.
select() function in D3. js is used to select the first element that matches the specified selector string. If any element is not matched then it returns the empty selection. If multiple elements are matched with the selector then only the first matching element will be selected.
D3 provides two top-level methods for selecting elements: select and selectAll. These methods accept selector strings; the former selects only the first matching element, while the latter selects all matching elements in document traversal order.
selectAll() function in D3. js is used to select all the element that matches the specified selector string. Syntax: d3.selectAll("element") Parameters: This function accepts single parameter HTML tag as a parameter. Return Value: This function returns the selected elements.
<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.
Not enough reputation to comment yet so I'll just put this here:
To expand on Micah's answer - the browser runs your code top to bottom, so if you write:
<div id="chart"></div> <script>var svg = d3.select("#chart").append("svg:svg");</script>
The browser will create a div with id "chart", and then run your script, which will try to find that div, and, hurray, success.
Otherwise if you write:
<script>var svg = d3.select("#chart").append("svg:svg");</script> <div id="chart"></div>
The browser runs your script, and tries to find a div with id chart, but it hasn't been created yet so it fails.
THEN the browser creates a div with id "chart".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With