[D3] Why must .append() come before .text()?

Tell us what’s happening:

Why must .append() come before .text() in order to render in the following block of code? I’m trying to dig into the documentation but am having a hard time understanding what is happening conceptually.

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

  // Add your code below this line
  d3.select('body')
    .selectAll('h2')
      .data(dataset)
    .enter()
    .append('h2')
    .text('New Item')
  // Add your code above this line
</script>
</body>

If I had to take a stab at it I would guess it is because .text([text]).append('h2') would try to append the h2 elements to text nodes(?) which I would presume is impossible. Please help me understand.

Documentation for reference:
Append and Text.

Challenge: Work with Data in D3

Link to the challenge:

Yes, that’s correct, it wouldn’t make any sense.

Glad to know, thanks!

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