I've been playing around with the example "Using D3.js to present XML as HTML Table", to try and learn the D3.js API. I think I am getting the hang of it, but I can't really understand what the .selectAll()
does, and the documentation on it is not very helpful.
If you look at the example, line 17: var td = tr.selectAll("td")
. I can also write this as tr.selectAll("tr")
and it will return the exact same table/page. In fact I can write tr.selectAll("SomethingCompletelyRandom")
and it will still work, but I can't remove the .selectAll()
.
What is going on here? What does .selectAll()
do? And how does it depend on the selector?
selectAll() function in D3. js is used to select all the element that matches the specified selector string. Parameters: This function accepts single parameter HTML tag as a parameter. Return Value: This function returns the selected elements.
svg. selectAll('rect') tells the browser to find the svg element and look inside it for any rectangles. If it finds rectangles, it returns them in a selection that is an array of elements.
d3. select selects the first matching element whilst d3. selectAll selects all matching elements. Both functions take a string as its only argument. The string specifies which elements to select and is in the form of a CSS selector string (e.g. div.
the API link you point to is using selectAll on a previous selection (it is a sub-selection) so it may not make sense for you to look at (and might be confusing.) The relevant part of the documentation to look at would be here, and more generally, the introduction to that selection documentation page, here.
The reason using both td
and tr
will work here is that the initial selection returns nothing in both of these cases (since the place you are selecting from, tr
, has had nothing appended to it yet.) It is standard practice to select what you will be creating, because when extending this to animations and updating it becomes extremely important.
I would recommend looking at the Three Little Circles and Thinking with Joins tutorials
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