Adding a DOM Element Using D3.js

Adding a DOM Element Using D3.js

D3.js Basic Example

In this example, you will use D3.js to add a DOM element to a basic webpage.

Start with a basic HTML webpage:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://d3js.org/d3.v6.min.js"></script>
    </head>
    <body>
        <p>
            Hello!
        </p>
    </body>
</html>

Next open the Developer Tools (Webkit Inspector).

Click on the "Elements" tab:

JavaScript Console for D3.js

This will give you the elements video of the webpage:

Chrome Elements View

Next (as of 2021), look for three dots lined up on top of each other that look like this:

Chrome Three Dots

Click on the three dots and select the "Show Console Drawer" option:

Chrome Show Console Drawer

This will open the JavaScript Console window while showing us the DOM elements of the webpage we are currently on.

Chrome DOM Elements and JavaScript Console

We are now ready to get started.

In the JavaScript Console, type d3.select("body").append("p"); and then hit return:

d3.select("body").append("p");

When you hit return, a paragraph "p" element is added to the HTML DOM.

You can see the added empty paragraph after the <p>Hello!</p> paragraph.

Add D3.js HTML Paragraph Element

Congratulations - you've added an HTML element to the DOM using D3.js!

Later we will add SVG elements just as easily as we did above.


D3.js Select Method

The first part of the JavaScript code that we wrote is .select("body").

The D3.js Select method uses CSS3 selectors to grab DOM elements.

To learn more about CSS3 selectors please check this out => CSS3 Selectors

D3 looks at the document and selects the first descendant DOM element that contains the tag body.

Once an element is selected, D3.js allows you to apply operators to the element you have selected.

These operators can get or set things like "attributes", "properties", "styles", "HTML", and "text content".


D3.js Append Operator

The operator that we used is .append("p").

The Append Operator appends a new element as the last child of the element in the current selection.

Since our current selection was d3.select("body"), the append operator added the "p" element last.

Add D3.js HTML Paragraph Element

The blue highlighted line is the 2nd child element of the body element.

The first child element of the body element is the paragraph element that contains the text "Hello!".