It seems logical that'#chart') does not work in your case, because the div you're aiming at is not on the current page.

You're loading some html as a string with jsdom, and try to replace the window variable to point at this new page.

But changing the window variable in your scope doesn't affect the d3 internal selectors. That's why you achieve to select your div with document.querySelector('#chart') and not directly'#chart')

As referenced in this post, you can make a selection on body, and then use subselections:

{jsdom} = require('jsdom')
d3 = require('d3')

# make a d3 selection on the new page body
document ="""<html>
      <div id="chart"></div>

data = [4, 8, 15, 16, 23, 42]

x = d3.scale.linear().domain([0, d3.max(data)]).range([0, 420])

# make a subselection within the body'#chart')
  .style("width",(d) -> x(d) + "px")
  .text((d) -> d))

Related Query

More Query from same tag