BarakChamo
BarakChamo

Reputation: 3575

d3.js - selecting the appended element

I'm trying to have all elements nested within a a single top-level group. I thought d3's selection is the last element appended but when i do this:

    svg
    .attr("width", vizW + margin.left + margin.right)
    .attr("height", vizH + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

I get this:

enter image description here

How can i have the group as the selection and not the SVG itself?

Thanks

Upvotes: 0

Views: 582

Answers (2)

sangil
sangil

Reputation: 1320

You thought right - the selection returned is the last element appended.

So to nest g elements inside a parent g, what you want to do is this:

var outer_g = svg
   .attr("width", vizW + margin.left + margin.right)
   .attr("height", vizH + margin.top + margin.bottom)
 .append("g") // this will cause the outer 'g' selection to be returned
   .attr('class', 'outer_g')
   .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var inner_gs = outer_g.selectAll('.inner_g')
   .data(the_data)
   .enter()
 .append('g') // this will cause 'inner_gs' to hold  a selection of the inner 'g' elements
   .attr('class', 'inner_g);

this will create the structure you desire

Upvotes: 0

BarakChamo
BarakChamo

Reputation: 3575

Well I guess i just had to dig a little,

In order to have the group as a selection it has to be declared seperately:

var viewport = svg.append('g')

Cheers

Upvotes: 1

Related Questions