Aadith Ramia
Aadith Ramia

Reputation: 10329

d3.js - Understanding enter()

I am trying out the following example:

<html>
    <head>
        <script src="//unpkg.com/d3"></script>
    </head>
    <body>
       <div class = "cities">
       </div>

    </body>
    <script>
        cities = ['san francisco', 'new york', 'seattle']

        d3.select("div.cities")
        .data(cities)
        .enter()
        .append("div")
        .html(d=>d)

    </script>
</html>

I was expecting this to add one div element corresponding to each city added inside the "cities" div element. But when I run this, I get the following:

enter image description here

Questions:

  1. Why are the new div elements getting added outside the "cities" div? How do I get them added inside "cities" div?
  2. Shouldnt there be 3 div elements? Why is div element for "san francisco" missing?

Upvotes: 0

Views: 544

Answers (2)

Troy
Troy

Reputation: 68

I've found the newer selection.join() to be a bit easier to understand when it comes to the enter/update/exit pattern when using D3.

<html>
        <head>
            <script src="//unpkg.com/d3"></script>
        </head>
        <body>
           <div class = "cities">
           </div>
        </body>
        <script>
            cities = ['san francisco', 'new york', 'seattle']
    
            d3.select("div.cities")
             .selectAll('div')
            .data(cities)
            .join( /* Add new data */
                   enter => enter.append("div").text( d=> d ),
                   /* Update existing data */
                   update => update.text( d => d ),
                   /* Remove data that no longer exists */
                   exit => exit.remove() )
    
        </script>
</html>

Upvotes: 1

ROOT
ROOT

Reputation: 11622

You need to add selectAll() before .data() what selectAll() function call do is bind your data elements to a DOM element once enter is called, here is an article explains it in depth:

https://www.d3indepth.com/enterexit/

<html>
        <head>
            <script src="//unpkg.com/d3"></script>
        </head>
        <body>
           <div class = "cities">
           </div>
    
        </body>
        <script>
            cities = ['san francisco', 'new york', 'seattle']
    
            d3.select("div.cities")
             .selectAll('div')
            .data(cities)
            .enter()
            .append("div")
            .html(d=>d)
    
        </script>
    </html>

Upvotes: 0

Related Questions