jeevan
jeevan

Reputation: 1

D3.js executing in different manner

I came from javascript background and I started d3.js While practice I written the following code.

html code :

<html>
 <head>
  <script type="text/javascript" src="d3.min.js"></script>
 </head>
 <body>
  <p id="firstP"></p>
  <p id="secondP"></p>
  <p id="thirdP"></p>
 </body>
</html>

js code :

var theData = [ 1, 2, 3 ];
var p = d3.select("body").selectAll("p")
       .data(theData)
       .enter()
       .append("p")
       .text( function (d) { return d; } );
console.log(p);

My motivation was, I want to append p nodes in between #firstP,#secondP,#thirdP elements. but after I execute above I am getting null how d3 handling this I didn't understand.

For my testing, I removed last p node from html file, the output coming 2 null values and 1 p node appending with corresponding data(3) .

I didn't understand how d3.js will handle this things.

can anyone help me.

Thanks.

Upvotes: 0

Views: 22

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109232

In your code, you're matching the data to the existing p elements. That is, your selection contains three p elements and your data contains three elements. Those are matched to the elements you've selected and the enter selection is empty. See this tutorial for more information on how selections work.

What you're trying to do isn't all that easy with D3 because you usually don't insert elements at specific positions, but append them to the DOM. However, you can use .insert() to achieve it. This is highly contrived though and I don't recommend that you do this in practice.

var theData = [ 1, 2, 3 ];
var names = ["firstP", "secondP", "thirdP"];
d3.select("body").selectAll("p")
    .data(theData, function(d) { return d; })
   .enter()
    .insert("p", function(d, i) { return d3.select("#" + names[i]).node(); })
   .text( function (d) { return d; } );

Complete demo here.

Upvotes: 3

Related Questions