Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get reference to SVG (child) elements nested in another SVG element (parent) using D3?

I have several groups (SVG G elements) nested in another group and I would like to get their ID's. I used the D3 javascript library to create the SVG and the code looks similar to this.

var body = d3.select("body");

var svg = body.append("svg")
    .attr("width", '100%')
    .attr("height", '100%')

var outerG = svg.append("g")
    .attr('id','outerG')

var innerG1 = outerG.append('g')
    .attr('id','innerG1')

var innerG2 = outerG.append('g')
    .attr('id','innerG2')

I tried to use childNodes attribute, but console.log(outerG[0].childNodes) gives me undefined. Could not find the right answer searching with google, could please someone give me a hint how to do that ?

like image 781
karlitos Avatar asked May 26 '13 23:05

karlitos


1 Answers

This will work:

console.log(outerG[0][0].childNodes);

See jsFiddle here

The reason you need two nested indices is that all selections are grouped implicitly. If you'd like to know the deeper reasons for this, or want to understand selections better in general, see this article

like image 151
Jonah Avatar answered Oct 04 '22 03:10

Jonah