Why is there a ".selectAll("rect")"

As you can see in the following code, Why put “.selectAll(“rect”)” before ".append(“rect”), there is no “rect” before we apppend “rect”, so could you tell me what the purpose of “.selectAll(“rect”)” is ? Thanks!

  **Your code so far**

  const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];

  const w = 500;
  const h = 100;

  const svg = d3.select("body")
                .attr("width", w)
                .attr("height", h);

     .attr("x", (d, i) => {
       // Add your code below this line
       return i*30

       // Add your code above this line
     .attr("y", 0)
     .attr("width", 25)
     .attr("height", 100);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36

Challenge: Dynamically Set the Coordinates for Each Bar

Link to the challenge:

I could be wrong, but I think what is going on there is that they introduced you to these things in the previous 2 or 3 challenges. They are trying to introduce you to the methods you would be using in a real project.

So for the sake of these challenges, it is “assumed” that the “rect” was already created in the previous challenges and exists.

At least that is my understanding after reading this challenge and the previous 2 or 3 challenges.

I haven’t gone through any of the Data Visualization with D3 curriculum prior to just now.

If I’m understanding it correctly, I think you are right, in a real project, you would first create the element, then select it, then append it. But for this challenge, don’t worry about that, just focus on the challenge itself.

In this code, you select all the existing rects and join them with the dataset in data(dataset) and get data that is not already represented by a rect from enter() and then append() a rect in the correct order for every new datum. selectAll() doesn’t fail because no elements is still a valid selection. The end result of this code is what you want for simple visualizations without animation: if you have data that represents bars in a bar graph, this code will create a bar for each datum.

See the documentation.

1 Like

Oh, yeah. So if there’s nothing to select you don’t get an error, it just returns empty and nothing is rendered on the screen.

Makes sense! :+1:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.