Reputation: 10329
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:
Questions:
Upvotes: 0
Views: 544
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
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