Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3.js selector not returning actual object

Tags:

d3.js

I am using d3.js v4. I have executed following code on google chrome browser's console.

var theData = [ 1, 2, 3 ]

var p = d3.select("body").selectAll("p")
          .data(theData)
          .enter()
          .append("p")
          .text("hello ");

console.log(p);

I was expecting a result like this:

enter image description here

But what I am getting is as shown below

enter image description here

Can someone please help me why this difference is there?

like image 587
Prashant Avatar asked Oct 04 '16 12:10

Prashant


People also ask

What type does D3 Select Return?

select() function in D3. js is used to select the first element that matches the specified selector string. If any element is not matched then it returns the empty selection. If multiple elements are matched with the selector then only the first matching element will be selected.

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

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.

What is are the selector method's in D3 JS?

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.

What is append in D3?

append() function is used to append a new element to the HTML tag name as given in the parameters to the end of the element. If the type that is given is a function then it must be evaluated for each element that is in the selection. Syntax: selection.


1 Answers

According to D3 4.x API:

Selections no longer subclass Array using prototype chain injection; they are now plain objects, improving performance.

So, in D3 version 4.x, selections are objects.

Also, it's worth mentioning that you're using the compressed version (https://d3js.org/d3.v4.min.js), which returns:

zi {_groups: Array[1], _parents: Array[1]}

In the normal version (https://d3js.org/d3.v4.js), the console.log return should be:

Selection {_groups: Array[1], _parents: Array[1]}

If you want to get something similar to what you had in D3 v3, use nodes():

var theData = [ 1, 2, 3 ]

var p = d3.select("body").selectAll("p")
          .data(theData)
          .enter()
          .append("p")
          .text("hello ");

console.log(p.nodes());
<script src="https://d3js.org/d3.v4.js"></script>
like image 68
Gerardo Furtado Avatar answered Oct 05 '22 21:10

Gerardo Furtado