dcsan dcsan - 3 months ago 11
Javascript Question

thinking in D3 - select vs append

Can someone explain like i'm 5 how this D3 syntax actually works?

var link = svg.selectAll('.link')
.data(links)
.enter().append('line')
.attr('class', 'link');


What it seems to do is just append links to the tree.

But how I read that is "select everything that is of class link, and append an attribute class=link". How it can select before those exist is puzzling.

Why is there a "select" before the items actually exist?
Does select really mean "insert"?

Answer

Line by line analysis would like below:

Select all the DOMs having class link.

var link = svg.selectAll('.link')

To all those links bind the data. Here data links is an array. links[0] is bound to first DOM if present. links[1] is bound to second DOM if present. ..so on

.data(links)
.enter()

Case 1: If the array links has 2 elements and the selection DOM elements has 0 elements. Then 2 line DOM will be appended to the svg DOM.

Case 2: If the array links has 2 elements and the selection DOM elements has 1 element. Then 1 new line DOM will be appended to the svg DOM.

Case 3: If the array links has 2 elements and the selection DOM elements has 2 or more elements. Then 0 new line DOM will be appended to the svg DOM.

    .append('line')
    .attr('class', 'link');

This would be a good read