Does anyone know what is the difference?
My understanding is that both would return the same selections.
However when I am doing an append, if I use selectAll("p") it does not work.
For instance, this works:
var foo = d3.select("body")
.selectAll("p")
.data([1, 2, 3, 4]);
foo.enter.append("p")
While this does does not work:
var foo = d3.selectAll("p")
.data([1, 2, 3, 4]);
foo.enter.append("p")
Why is it that the latter doesn't work?
d3. select selects the first matching element whilst d3. selectAll selects all matching elements. Both functions take a string as its only argument.
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.
D3 provides two top-level methods for selecting elements: select and selectAll. These methods accept selector strings; the former selects only the first matching element, while the latter selects all matching elements in document traversal order.
The short answer here is, "Because there's nothing to append to." While you're correct that d3.selectAll("p")
and d3.select("body").selectAll("p")
will select the same existing nodes, selecting the body
element first sets the context for new nodes added with the .append()
method.
Without selecting body
, you have no point in the DOM tree to insert your nodes - I'm guessing that d3 attempts to append the new nodes to the document
object, which results in the HIERARCHY_REQUEST_ERROR
discussed here.
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