Skip to content

Can’t append simple svg to body element

I know this is a super easy question. But I am apparently missing something super obvious. I just want to create an svg element with D3 and see it on my page. My index.htmllooks like this:

<!DOCTYPE html>
<html lang="en">

        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="node_modules/d3/dist/d3.min.js"></script>
        <script src="selections.js"></script>
        <link rel="stylesheet" href="style.css">
        <title>D3 Selections</title>



Whereas my selections.js looks like this:

console.log("This appears...")

w = window.innerWidth
h = window.innerHeight

// // make the svg

const svg ="body")
    .attr("height", h)
    .attr("width", w)
    .attr("class", "svg")

The first console.log() is still visible in the console. But I cant see the svg. I know I am missing something super clear, but I just cant see it at the moment:/


I don’t know d3.js that well but you should probably wait for the DOM to load:

console.log("This appears...");

w = window.innerWidth;
h = window.innerHeight;

document.addEventListener('DOMContentLoaded', e => {
  // // make the svg
  const svg ="body")
    .attr("height", h)
    .attr("width", w)
    .attr("class", "svg");