What am I missing, or doing wrong, that I do not see the text (Hello) five times on the page?
index.html
<html>
<head>
<title>Data Binding</title>
</head>
<body>
<h1>D3.js</h1>
<script src="https://d3js.org/d3.v7.min.js"></script>
<script src="data-script.js"></script>
</body>
</html>
data-script.js
var dataset = [1, 2, 3, 4, 5];
d3.select('body')
.data(dataset)
.enter()
.append('p')
.text("Hello");
CodePudding user response:
To insert <p>
nodes within <body>
per the length of the dataset
array you can create an empty selection within the the selection of <body>
e.g.:
// data-script.js
var dataset = [1, 2, 3, 4, 5];
d3.select('body')
.selectAll("p") // <----- this is the extra line you need
.data(dataset)
.enter()
.append('p')
.text("Hello");
<html>
<head>
<title>Data Binding</title>
</head>
<body>
<h1>D3.js</h1>
<script src="https://d3js.org/d3.v7.min.js"></script>
<!-- <script src="data-script.js"></script> -->
</body>
</html>
The selector "p"
can be whatever you need e.g. a class ".testParagraph"
.