Reputation: 1950
I'm trying to get d3 v4 to work basic simple rendering as v3 worked before, I'm getting null object. Here's a simple version of the code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.4.0/d3.min.js"></script>
<script>
var dataset = [23, 45, 66, 77, 88, 99];
var svg = d3.select("body").append("svg").attr({width: 500, height: 500});
console.log('svg : '+svg);
</script>
Result of the above code is:
svg : null
Writing the same code with v3, the result
svg : [object SVGSVGElement]'
What am I missing here? I'm following the tutorials and most of them are in v3.
Upvotes: 3
Views: 847
Reputation: 102174
Despite all answers (including the current accepted answer) saying otherwise, you can pass an object to attr
and style
in D3 version 4.x, as long as:
First, you reference "selection-multi":
<script src="https://d3js.org/d3-selection-multi.v1.min.js"></script>
Second, you use attrs
and styles
, as a plural:
d3.select("body").append("div")
.attrs({
title: "A cheery, timeless greeting.",
class: "greeting"
})
.text("Hello, world!");
So, in your code, it should be:
var svg = d3.select("body")
.append("svg")
.attrs({width: 500, height: 500});
Here is a demo to show you that it works:
var svg = d3.select("body")
.append("svg")
.attrs({width: 500, height: 500});
console.log('svg : ' +JSON.stringify(svg));
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-selection-multi.v1.min.js"></script>
Upvotes: 1
Reputation: 3577
The attr
function can take two arguments - the attribute name and the attribute value. Try this instead:
var dataset = [23, 45, 66, 77, 88, 99];
var svg = d3.select("body").append("svg")
.attr("height", 500)
.attr("width", 500);
console.log('svg : '+svg);
Upvotes: 4