The difference between select (). Append () and select (). Data (). Enter (). Append ()?
If I have this HTML:
<body> <div class="parent"> </div> </body> And execute this code:
d3.select('div') .append('span') .html("I'm appended to div.parent") This is my final HTML.
<body> <div class="parent"> <span>I'm appended to div.parent</span> </div> </body> But if I execute this code:
d3.select('div') .data([0,1]).enter() // This line of code was added. .append('span') .html("I'm appended to document") span added to the HTML document.
<body> <div class="parent"> </div> </body> <span>I'm appended to document</span> I know that selectAll() overrides the parent element, so my question is not why the second statement does not work, but why does the first one work? According to this logic, d3.select('div').append('span') should not override the parent element and add span to the document element. Why is this not so?
The append method simply adds something inside each selected item, making the first example quite intuitive.
In the second example, you know that the call to enter returns a selection filled with "placeholders" for each new element that needs to be added based on data . But the placeholders don't really explain what is happening. The documentation for .enter() explains:
Another way to think about entering placeholder nodes is that they are pointers to the parent node (in this example, the body of the document); however, they only support adding and pasting. After elements have been inserted, their indices will reflect new positions and do not have to start from scratch or be continuous.
So, in both examples, the parent node is still <body> , simply because you haven't connected two or more select / selectAll . The difference between the two is as follows: append ed to is the selected <div> in the first example and the original parent of the node selection in the second example.
Thanks for the nice question, by the way; it made me think more about how and why this material works, and not just what it does.