I recently started using d3.js
to write some scripts to manipulate SVGs. So most of the time I refer d3 documentation and find the solution. However I cannot understand why d3.select
function return array of arrays. For example let's say i have an SVG
element and if I do d3.select("svg")
, it returns [[svg]]
so I have to do d3.select("svg")[0]
. The documentation says
One nuance is that selections are grouped: rather than a one-dimensional array, each selection is an array of arrays of elements. This preserves the hierarchical structure of subselections
Then says we can ignore it most of the time.
This preserves the hierarchical structure of subselections
mean?
Thanks in advance.
You shouldn't need to know or care how the object d3.select
returns is structured internally. All you need to know is which methods are accessible in that object, which is what the documentation describes.
Say you have this document:
<div>
<span>1</span>
<span>2</span>
</div>
<div>
<span>3</span>
<span>4</span>
</div>
If you select all <div>
elements with d3.selectAll
var div = d3.selectAll("div");
the div
is a d3 selection object of size 2, one for each <div>
element in the document.
But if you now generate a subselection from this selection object
var span = div.selectAll("span");
a search is made for matching elements within each element in the div
selection, and the structure is preserved -- i.e., the span
selection will contain the same number of elements as the div
selection it was based on, and each of these will consist of a selection of elements found in that element.
So in this case, span
will contain two selections (first <div>
and second <div>
), each of which will contain two elements(1 and 2 in the first, 3 and 4 in the second).
As for select
, it is the same as selectAll
except it stops after finding one match; its return is structured exactly the same way, however.
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With