0

This question is on d3, v5.

I'm trying to attach the class of the parent element to the child as I create the child element.

var data = [
  [0,10,20],
  [10,20,30],
  [45,55,65]
];

var svg = d3.select("svg");
var rowHeight = 15;

// dummy domain
var xScale = d3.scaleLinear().range([0,100]).domain([0,100]);

var rows = svg.selectAll("g")
  .data(data)
  .enter()
    .append("g")
    .attr("transform", (d,i)=>`translate(0,${rowHeight*i})`)
    .attr("class", (d,i)=>"r"+i)
  ;

rows.selectAll("g")
  .data((d)=>d)
  .enter()
    .append("g")
    .attr("transform", (d,i)=>`translate(${xScale(d)})`)
    .attr("class", (d,i)=>"c"+i) // how to get class = r* here?
    // tried d3.select(this.parentNode).attr("class") but doesn't work
  ;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width=500 height=100></svg>

Resulting HTML

I tried d3.select(this.parentNode).attr("class") but that's throwing an error.

The basic idea is to get the row and column classes into each of the "g" elements, so further selections will be easier.

Thank you!

isherwood
  • 58,414
  • 16
  • 114
  • 157
mrbrahman
  • 455
  • 5
  • 18
  • Possible duplicate of [How to access the parentNode of a d3.js selection?](https://stackoverflow.com/questions/10607732/how-to-access-the-parentnode-of-a-d3-js-selection) – ksav Jan 07 '19 at 14:02

1 Answers1

1

.attr("class", function(d,i) { return d3.select(this.parentNode).attr("class"); })

As described in a similar question, this.parentNode gives you the <g> domain tree element itself, but what you need is a D3-wrapped object that supports calls to D3-specific functions such as .attr.

Also note that this isn't defined as usual in the arrow shorthand format but points to the surrounding context, as described in MDN.

Florian
  • 4,821
  • 2
  • 19
  • 44
  • Thanks! This is interesting. As you can see, I tried that exact line, the only difference is I used the shorthand => arrow syntax. Looks like `this` is not available in the shorthand syntax. Got to read up on that now :-) – mrbrahman Jan 07 '19 at 14:16
  • 1
    [MDN says](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this): `An arrow function does not have its own this; the this value of the enclosing lexical context is used`. Meaning that `this` here points to the Window, not to the active domain tree element. – Florian Jan 07 '19 at 14:31