ray
ray

Reputation: 37

'undefined' when using attr method in d3.selectAll

I'm using a 'd3-select' package for changing my plot, and I'm blocked by this strange error.

it works just fine when I used 'attr' method after selectAll('path'), but it breaks when I used it on selectAll('line'). And I figured out that 'attr' on selectAll('line') receives nothing.

Code

const paths = this.$gPlot.selectAll('path');
console.log('paths =', paths);
paths.attr('d', path => console.log(path)); // there's two path elements

const lines = this.$gPlot.selectAll('line');
console.log('lines =', lines);
lines.attr('y1', line => console.log(line)); // there's three line elements

Result on console

image

I don't know what's going on here.

Upvotes: 0

Views: 1261

Answers (1)

Chris Applegate
Chris Applegate

Reputation: 762

When you supply a function to functions like attr(), the first argument of the function is the data that is bound to the element, which has usually been previously assigned by calling data() on the group. It is not the SVG element itself.

In your case, there is data bound to the paths, but not the lines, so you are getting undefined on the lines when calling the function. To get the reference to the SVG element via the function, use:

lines.each(function() {
    console.log(this);
})

You have to use a full function, not shorthand, for the this to be correctly scoped

Upvotes: 4

Related Questions