Method Chaining

Learn about method chaining and how it works.

Introduction

Let’s dive into a fundamental concept of D3.js, method chaining. It is the technique where we connect different methods with a period. When we apply a method on an object, it performs an operation and returns an object on which another method can be called. This process is known as method chaining. We will use method chaining throughout this course.

Example

Let’s look at an example of method chaining to see it in action.

Method chaining code

Let’s take a look at the explanation of the above code to understand how it works.

d3.select(“body”)

In line 1, the select("body") method will select the DOM element body in HTML and return this selection to the next method which is append() .

append(“div”)

The code append("div") method will only work with the body element that it has received. Now it will create a new element div, add it to the body tag, and pass this element into the next method in the chain, which, in this case, is text().

text(“hello method chaining”)

The text("hello method chaining") method receives the div element and adds the text, “hello method chaining” into it.

After the execution of the above code, our HTML file will look like this.

Press + to interact
<body>
<div>
hello method chaining
</div>
</body>