Manipulating DOM Elements

Get a brief introduction to the text(), append(), remove(), style(), and attr() methods.

text() method

Let’s take a look at the text() method which manipulates DOM elements and is generally used to add or modify the text inside DOM elements.

Text method code

In line 1 in the above example, we are manipulating the DOM element div by adding text into the selected div tag using the text() method.

append() method

We can add a new HTML element in D3.js by using the append() method. It creates a new HTML element and inserts it at the end of the selected element. Let’s create a new div element inside the body tag and add text to it using the text() method.

Append() method code

In the above example, one div tag is already present inside the body tag in the HTML file. In line 1 in the Javascript tab using the append() method, we have added a new div tag inside it. Then, we have added the text, “Appending new tag” using the text() method.

remove() method

The remove() method is very important when it comes to DOM manipulation. It is used to remove any HTML element. In the following example, let’s use the remove() method to remove the first div tag.

Remove() method code

In line 1 in the above example, select("div") selects the first div tag and then the remove() method removes it from the HTML file. Therefore, we will only see 2nd div tag in the output screen.

style() method

Styling is an important aspect of DOM manipulation and D3.js provides the style() method to give style to DOM elements. Let’s take a look at the following example. We will add color and change the size of the text using the style() method.

style() methode code

In line 1 we have selected the div tag using the select() method, then we applied the blue color to the text, and changed the font-size to 30px.

attr() method

There is another important method, attr(), which is used to manipulate the DOM elements, although, we will see its real power in the upcoming lessons. For the time being, let’s take a look at the following example. In the previous example, we have used style twice to change the color and font size of the text. We can do this by calling the attr() method once and using CSS.

attr() method code

Apart from this, the attr() method defines attributes of a geometrical figure, i.e., height, width, radius, etc., which we will see in future lessons.