Reputation: 83
I would like to append elements in a loop to a "root"-div and then go back up the DOM-tree to append another element / set the text (in D3.js).
The desired structure:
root > div > div
> text
> div > div
> text
> ...
The code:
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js">
for (var i = 0; i < 10; i++) {
d3.select("#root")
.append("div")
.append("div")
.parentNode
.text("text");
}
</script>
The error-message:
[...].parentNode is undefined
Is there a way in D3 to go up the tree after appending an element?
Upvotes: 3
Views: 1986
Reputation: 108527
I assume your code above is just for illustration because it could be written:
d3.select("#root")
.append("div")
.text("text")
.append("div");
That said, you could use:
var div = d3.select("#root")
.append("div")
.append("div")
.select(function(){
return this.parentNode;
})
.text("text");
Problem with this is the .text
is going to overwrite the child div.
So, to avoid that how about:
var div = d3.select("#root")
.append("div")
.append("div")
.select(function(){
return this.parentNode;
})
.insert("span","div")
.text("text");
Example here.
Upvotes: 5