Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
46
rated 0 times [  53] [ 7]  / answers: 1 / hits: 30509  / 12 Years ago, tue, october 23, 2012, 12:00:00

I have a problem with inserting new siblings to existing elements.



I have this structure



<svg> 
<g>
<path class=data></path>
<path class=data></path>
</g>
</svg>


and want this structure



<svg> 
<g>
<path class=data></path>
<text></text>
<path class=data></path>
<text></text>
</g>
</svg>


but if I use the d3.js insert function



d3.select(g).insert(text, path.data);


i get the following (despite selecting by class name)



<svg> 
<g>
<text></text>
<path class=data></path>
<path class=data></path>
</g>
</svg>


any ideas?


More From » dom

 Answers
10

First of all, it's worth noting that the second argument in the insert function is a before selector. Furthermore, chained operations act on the left hand result.



So you have done



// select all the g elements (only 1)
d3.select(g)
// For each g, insert a text element before path.data
.insert(text, path.data);


You want to perform an operation for each child .data, so you need to select each of the .data elements and perform an action for each of them. I'm not entirely sure how d3 expects you to insert an element after a specific child. I find it much easier to use the DOM API to do the element creation and insertion, but using the d3.each function to iterate over a selection.



d3.selectAll(g > .data).each(function () {
var t = document.createElement('text');
this.parentNode.insertBefore(t, this.nextSibling);
});​

[#82402] Monday, October 22, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
micayla

Total Points: 148
Total Questions: 92
Total Answers: 109

Location: Aruba
Member since Sat, Oct 2, 2021
3 Years ago
micayla questions
Fri, Dec 24, 21, 00:00, 2 Years ago
Thu, Apr 16, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
;