Accepted answer

this is an interesting question: normally, the answer here would be just "select the div you want by id or any other css selector that suits you" (or, since that this has been answered many many times, just a comment and a vote to close). the basis for that answer is that this...

var svg ="body").append("svg")

... will append the svg at the end of the body. so far, nothing new or difficult.

but why did i said that this is an interesting question?

because of the funny way (if you don't mind me saying so) you tried to select the div: you thought that d3 would create the chart inside that div just by putting the respective script inside it.

of course putting the script inside the container div is not the way of doing this. but just for the sake of curiosity, there is a way of doing what you thought you were doing (again, selecting the element that contains the script): by using document.currentscript, which:

returns the element whose script is currently being processed.

so, all we need in your situation is:

var container = document.currentscript.parentnode;
var svg =

which appends the svg in the <div> (or any other containing element) that contains the <script>.

here is a basic demo:

<script src=""></script>
  <h3>i am div 1</h3>
  <h3>i am div 2, i have a chart</h3>
    var container = document.currentscript.parentnode;
    var svg =
    var data = d3.range(10).map(d => math.random() * 150);
    var scale = d3.scaleband()
      .range([0, 300])
    var bars = svg.selectall(null)
      .style("fill", "steelblue")
      .attr("x", d => scale(d))
      .attr("width", scale.bandwidth())
      .attr("height", d => 150 - d)
      .attr("y", number)
  <h3>i am div 3</h3>
  <h3>i am div 4</h3>

note that document.currentscript doesn't work on ie (if you care for ie, just give the div an id and select it).

Related Query

More Query from same tag