D3.js is a javascript library that is designed for creating data driven web pages. It can be found at https://d3js.org/.
To get started with D3.js we need to include it on one of our web pages. I would recommend a site like https://plnkr.co to start experimenting with the library.
On a new project we can include in our <head> tags the most recent version of D3 with
<script src="https://d3js.org/d3.v4.min.js"></script>
One of the most simple things we can do with D3 is select a DOM element, to do that we use the d3.select(selector) method which gets the first element that it finds that matches the search that it is passed. The search selector uses standard DOM selectors. The most basic three look like this:
In this example I have a div with the id of "start". The in the script, I call select on "#start" which finds the first element with the id of "start" (your id's should be unique by the way), then chaining off that selection, the text is changed to "Hello, World!".
To get started with D3.js we need to include it on one of our web pages. I would recommend a site like https://plnkr.co to start experimenting with the library.
On a new project we can include in our <head> tags the most recent version of D3 with
<script src="https://d3js.org/d3.v4.min.js"></script>
- Tag Type: tagname
- ID of a tag: #idname
- Class: .classname
Once you have selected a tag, you can start manipulating it. Probably the simplest thing is to change it's text, you can chain off the selection using the selection.text() method. Here is an example
<html>
<head>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div id="start"></div>
</body>
<script>
d3.select("#start").text("Hello, World!");
</script>
But what if we want to manipulate multiple elements? We can use the selectAll(selector) method. This is where D3 starts to get a little more powerful. In the next example, I have 3 divs with the class of "container". By using selectAll, I can select all three and work on all of them at the same time.
<html>
<head>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div class="container"></div>
<div class="container"></div>
<div class="container"></div>
<script>
d3.selectAll(".container").text("Hello, World!");
</script>
</body>
</html>
The result of this page is our hello world message 3 times. You can find a list of element modification methods in the d3 api reference. These include the ability to manipulate html, text, classes, css styles, attributes and properties of elements. One very important method group that can be done on selections, we will talk about in the next post: Element creation and removal.
Comments
Post a Comment