22

I'm having an issue trying to put a circle and a text inside a group (same level, not inside each other) in the .enter() context

var categorized = g1.selectAll("g.node").data(dataset, function(d){return d.id})

categorized
.enter()
    .append("g")
    .attr("id", function(d,i){return d.id;});

categorized
.enter().append("circle")
    .style("fill", "#ddd");
// throws an error

categorized
.append('text')
    .text(function(d,i){return d.count});
// this is working but is an update so I have to remove the text on exit

Is there a way to get back to the parent, sg like this:

categorized
.enter()
.append("g")
.append("circle")
.getBackToParent // the g
.append("text");
mikmikmik
  • 500
  • 1
  • 5
  • 10

1 Answers1

39

Just assign the parent d3 wrapper to a variable:

var g = categorized.enter().append("g");
g.append("circle").style("fill", "#ddd");
g.append("text").text(function(d,i){return d.count});
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Thanks. It worked. I had a data-binding problem earlier and though using a var with the enter context was part of the problem but it's not. – mikmikmik Sep 01 '12 at 18:41
  • This is very useful in `svg`. But what about in `html`, for example to alternate `
    ` and `
    ` tags?
    – leonard vertighel Jun 09 '14 at 15:35
  • @leonardvertighel: Not sure what you mean, you might want to ask a new question. – Felix Kling Jun 09 '14 at 18:09
  • Thanks, I asked here http://stackoverflow.com/questions/24116328/how-do-i-create-a-definition-list-with-d3-js : basically I would like to create a list of alternate nodes `
    key
    value
    key
    value
    ...` without a wrapper element
    – leonard vertighel Jun 09 '14 at 18:47
  • That is amazing but I was hoping it would be possible some other way. – Alper Jan 25 '16 at 17:41