D3.js selectors d3.select
by Imabot
HTML
<script src="https://d3js.org/d3.v5.min.js"></script>
<h1>My first bar chart with D3.js</h1>
<div id="bar-chart"></div>
<button id="change-button">Change data</button>
CSS
#bar-chart svg { background-color: Gainsboro; }
#bar-chart .bars { fill: LightSkyBlue; }
JavaScript
// Set of data
var dataset1 = [31, 64, 42, 28, 16, 32, 64, 10];
var dataset2 = [10, 20, 50, 90, 90, 50, 20, 10];
// Create our SVG container with grey background
var svg = d3.select("#bar-chart")
.append("svg")
.attr("width", 200)
.attr("height", 100);
// create a group for the bars
var bars = svg.append('g')
.attr('class', 'bars');
// Bind data to chart, and create bars
bars.selectAll('rect')
.data(dataset1)
.enter()
.append('rect')
.attr('x', (d,i) => i*25 )
.attr('y', (d) => 100-d)
.attr('width', 20)
.attr('height', (d) => d);
// When the button is pressed
d3.select('#change-button').on('click', function() {
bars.selectAll('rect')
.data(dataset2)
.attr('x', (d,i) => i*25 )
.attr('y', (d) => 100-d)
.attr('width', 20)
.attr('height', (d) => d);
})