Richard
Richard

Reputation: 65550

D3.js: concatenate selections?

Is there a way in D3 to concatenate selections?

Use case: I'd like to add a mouseover event to both the update and enter selections of a particular selection.

I can do this as follows:

var s = d3.selectAll('.yellow').data(myData);
s.on('mouseover'...
s.enter().append('path').attr('class','yellow').on('mouseover'... 

But I'd prefer to do it with one line of code.

Upvotes: 6

Views: 2092

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109242

In this particular case you don't need to concatenate -- the enter selection merges into the update selection after it's been called, so all you need to do is handle .enter() before the update selection.

In general, you can't really concatenate selections as such, but in practice this isn't really necessary. You can either modify the selection condition to select all the elements you need, or, if this is not possible, use .call() to run a function on all selected elements. This way you don't need to repeat the code to set attributes etc.

Upvotes: 8

Related Questions