In this HTML document:
<html>
<body>
<div id="viz">
</div>
<body>
</html>
Applying this code:
var viz = d3.select('#viz').selectAll('p').data([0])
.enter().append('p');
Gives this result:
<html>
<body>
<div id="viz">
<p></p>
</div>
<body>
</html>
This is because selectAll()
defines a parent element based on the preceding select
method, which is select('#viz')
. In that way:
console.log(viz[0].parentNode) // <div id="viz">
Whereas if you execute the following code in the first HTML document:
var viz = d3.select('#viz').select('p').data([0])
.enter().append('p');
It gives you this result:
<html>
<body>
<div id="viz">
</div>
<body>
<p></p> <!-- your p element is appended to <html> as its parent element
</html>
Since a selectAll()
is required to redefine your selection's parent element, the parent element of your selection is still <html>
which is set by default. If we log the selection's parent node:
console.log(viz[0].parentNode) // <html>
Remember that selections are arrays (groups) of arrays of elements. Writing viz[0]
gets the first group of elements, not the first element of your selection. To obtain the first element you should write:
console.log(viz[0][0].parentNode)
Which will give you the parent element of that specific element in the DOM tree, not in your d3 selection group.