While this isn’t very complex right now, we can expect that things will get harder and more difficult to reason as we scale. Here’s why we need to consider D3.

Selections in D3

Notice how when we wanted to manipulate multiple elements in the DOM we had to map over them. D3 selections allow us to query one or more elements on the page and allows us to manipulate the whole selection without the need for iteration on our part.

It uses standard CSS selector syntax, so you can expect to query an element by it’s name, a class with .about-me, an id with #list, and so on.

We can select elements from the DOM with either:

select() takes one element from the DOM. If there are multiple matches, only the first one will be taken.

selectAll() takes all elements from the DOM.

Example

Let’s take a look at this with a code example. Doing the same as our vanilla JavaScript example can be done in one line:

constli=d3.selectAll('li').style('font-weight','bold');

As you can see, it returns a collection of elements which we can chain into other methods such as style.

If we change this to be select instead of selectAll, you’ll notice that I'm a powerlifter is the only li that gets bolded – this is expected as it’s the first li in the DOM.

Appending a new list item

To further show the power of selections, consider how we may want to add a new lito the DOM with JavaScript:

As you can see, we’re not just limited to the initial selection. We can continue to make sub selections and get more specific about our implementation.

What do Selections Look Like?

Let’s use console.log to inspect our select query to look at what gets returned:

{groups:[Array(1)]parents:[html]}

If we expand groups, you’ll see that it returns our ul as per the selection. If we changed our selection to be selectAll('li'), the groups returns an Array containing a collection of lis inside of a NodeList(3).

constli=d3.selectAll('li');console.log(li);

groups:Array(1)0:NodeList(3)0:li1:li2:liparents:[html]

Naturally, the _parents object contains the parent for this selection, being the root html object.