Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3.js: Differences between select("body").selectAll("p") and selectAll("p")?

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?

like image 404
Jia He Lim Avatar asked Dec 12 '11 22:12

Jia He Lim


People also ask

What do the select () and selectAll () functions in D3 do?

d3. select selects the first matching element whilst d3. selectAll selects all matching elements. Both functions take a string as its only argument.

What does D3 selectAll return?

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.

What is or are the main selection in D3?

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.


1 Answers

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.

like image 146
nrabinowitz Avatar answered Oct 30 '22 02:10

nrabinowitz