1

I have svg element of <circle> inside <g>, and I want to give each circle tag a class like this:

 <g class="parent">
    <circle class="circle_0"></circle>
    <circle class="circle_0"></circle>
    <circle class="circle_0"></circle>
    <circle class="circle_0"></circle>
  </g>
  <g class="parent">
    <circle class="circle_1"></circle>
    <circle class="circle_1"></circle>
    <circle class="circle_1"></circle>
    <circle class="circle_1"></circle>
  </g>
  <g class="parent">
    <circle class="circle_2"></circle>
    <circle class="circle_2"></circle>
    <circle class="circle_2"></circle>
    <circle class="circle_2"></circle>
  </g>

the number after circle_ comes from the order of its parent <g>, but each parent has the same class name.

I am creating them like this and right now, every <circle> has the same class:

var g = svg.append("g")
var parentElement = g.selectAll(".parent")
    .data(data)
    .enter().append("g")
    .attr("class", "parent");

parentElement.selectAll(".circle")
    .data(function(d,i) { return d; })
    .enter().append("circle")
    .attr("class", "circle")

How can I achieve this?

kay
  • 1,369
  • 4
  • 15
  • 27

1 Answers1

1

Since you're using D3 v3 you can use the third argument, which is the parent's index, to set your classes:

.attr("class", function(d,i,p){
    return "class_" + p;
});

Check the snippet:

var data = [[1,1,1,1],[1,1,1,1],[1,1,1,1]];
var svg = d3.select("body");
var g = svg.append("g")
var parentElement = g.selectAll(".parent")
    .data(data)
    .enter().append("g")
    .attr("class", "parent");

parentElement.selectAll(".circle")
    .data(function(d,i) { return d; })
    .enter().append("circle")
    .attr("class", function(d,i,p){
  console.log("circle_" + p);
  return "circle_" + p;
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

PS: this will not work on D3 v4 (see here).

Community
  • 1
  • 1
Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
  • 1
    Thanks again Gerardo! wow that was easy. I did not even know that there is the 3rd argument. – kay Jan 05 '17 at 07:54