Adding a DOM Element

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:

 1<!DOCTYPE html>
 3  <head>
 4    <script type="text/javascript" src="d3.v2.min.js"></script>
 5  </head>
 6  <body>
 7    <p>Hello!</p>
 8  </body>

Next open the Developer Tools (Webkit Inspector). To make things easier, click on the icon that looks like an arrow with three lines. This will give you the JavaScript Console and the HTML elements in one view. The button is at the very bottom of the image and is colored blue when you click on it.

JavaScript Console for D3.js

In the JavaScript Console, type the following and then hit return:"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.

D3.js Added a Paragraph P HTML 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"body"), the append operator added the "p" element last.

D3.js Added a Paragraph P HTML 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!".

If you found this D3 Tutorial helpful, you'll enjoy these FREE videos: