Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript D3.js Selections with D3.js Selections

Qian Chen
Qian Chen
33,579 Points

Why style() function can be invoked on the returned array?

It seems d3.select/selectAll return an array of matched dom elements. If this is the case, why the style() function can be invoked on an array?

Thanks, Elgs

2 Answers

They actually return an array of arrays, which D3 also "binds additional methods to": see Selections - Operating on Selections.

Those 'additional methods' would include the style() function, among others like attr(), which was also used in the video. Presumably the style method is scripted so that it would operate only on selections of DOM elements that can be styled.

Jeff Everhart
Jeff Everhart
21,732 Points

This is a good question, but I think it has a lot to do with the way that d3 was built. As a library that extends JS, it seems that this is something the creators intentionally designed. Since the select and selectAll methods return an array it only makes sense that you would be able to use the other d3 methods to operate on arrays automatically.