Append SVG canvas to element other than body using D3

18,548

You're trying to select #container before it exists. You'll need to put your code in an onload or move the script below #container in the page.

Share:
18,548
Gilman
Author by

Gilman

Updated on June 21, 2022

Comments

  • Gilman
    Gilman almost 2 years

    Is it possible to append an SVG canvas to an element other than <body> using D3.js if the script is not inside that element?

    For example, the code below does not work:

    <html>
    <body>
    <script src="../../d3.v2.js"></script>
    <script>
        var vis = d3.select("#container")
            .append("svg:svg")
              .attr("width",w)
              .attr("height",h);
    </script>
    
    <div id="container"></div>
    
    </body>
    

    All examples I have seen use d3.select("body").append.... but clearly we don't always want to append the canvas immediately to the body.

    I found that if the <script> is inside the container div then I can use d3.select("#container") but it seems strange to me that I would have to include my script inside of the specific container(s) where I want the canvas.

  • bobthyasian
    bobthyasian over 11 years
    Also, script includes belong in the header.
  • Zikes
    Zikes over 11 years
    That's a debatable point, as some people like to put all or most scripts at the end of the page to prevent it from blocking the page load & render.
  • Gilman
    Gilman over 11 years
    Wonderful, thank you for the quick response. Works like a charm - also helps me better understand how the d3 selectors work.
  • eremzeit
    eremzeit over 9 years
    I'm not sure why but all the d3 examples I've seen will put the <script> elements at the beginning of the body. Doesn't seem like it's really providing a great example on how to integrate with the rest of the page.
  • Zikes
    Zikes over 9 years
    Most examples are more concerned with creating short, functional example code with little to no cruft. By putting the script tag in the body the code can immediately run and select the body without the need of an onload or document ready wrapper. Not ideal in production, but people ought to know that.
  • Daghan ---
    Daghan --- almost 7 years
    Huge! Thanks a million. I have been stuck on this for 48 hours and was going nuts