Ayan Ayan - 4 months ago 23
jQuery Question

First data is ignored without using selectAll in d3.js

Snippet 1



<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8">
<title>D3 Test</title>
<script type="text/javascript" src="http://d3js.org/d3.v3.js"></script>
</head>

<body>
<script type="text/javascript">
var data = [];
for (i = 0; i < 3; i += 1) {
data.push(i);
}
d3.select('body')
// .selectAll('p')
.data(data)
.enter()
.append('p')
.text(function(d) {
return d;
});
</script>
</body>
</html>





Snippet 2



<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8">
<title>D3 Test</title>
<script type="text/javascript" src="http://d3js.org/d3.v3.js"></script>
</head>

<body>
<script type="text/javascript">
var data = [];
for (i = 0; i < 3; i += 1) {
data.push(i);
}
d3.select('body')
.selectAll('p')
.data(data)
.enter()
.append('p')
.text(function(d) {
return d;
});
</script>
</body>
</html>





The code
.selectAll('p')
is commented in the first snippet. I could not figure why the first data is ignored due to that reason.

I am a newbie to d3.js and what I understood ,as I don't have a
p
tag in my HTML the
.selectAll('p')
returns an empty selection and
p
are appended as per my data count.

Thanks in advance.

Answer

To understand what happened, you have to understand what is an "enter" selection. This example in the documentation briefly explains both the "enter" selection and why you have to selectAll("p") in your second snippet, even if you don't have any <p> in the document:

The role of placeholders in "enter" selections

Now, let's see your snippets:

Your first snippet:

In your first snippet, data is [0, 1, 2]. So, you have 3 elements. When you select the body, there is clearly a body in the DOM. So, you associate the first datum (0) to this element (body). Now, you have 2 data not associated to any DOM element: 1 and 2. These two data are your "enter" selection. When you append the <p>, your enter selection has only those two numbers.

Your second snippet

In your second snippet, data is again [0, 1, 2]. The difference is that now you select all <p>... but there is none. This is the "placeholder" in the example I linked. As there is no <p> in the DOM to associate with the data, your enter selection has all 3 data: 0, 1 and 2.

As I wrote in the example:

If in your "enter" selection you select something that doesn't exist, your "enter" selection will always contain all your data.