How to select the parent element of the current element in d3.js

I want to access the parent element of the current element

Here is the HTML structure

svg g id=invisibleG g circle g circle g circle 

Basically I want to add text inside the circles when I hover over them.

So, I want something like this to hang in any particular circle

 svg g id=invisibleG g circle --> radius is increased and text presented inside that text g circle g circle 

In hover mode, I can select the current element via d3.select (this), How can I get the root element (g in my case)?

+46
javascript
Dec 17 '13 at 18:29
source share
2 answers

You can use d3.select(this.parentNode) to select the parent element of the current element. And to select the root element, you can use d3.select("#invisibleG") .

+82
Dec 17 '13 at 18:36
source share

To get the root element g (like dots), you can get using:

 circle = d3.select("#circle_id"); g = circle.select(function() { return this.parentNode; }) 

This will return a d3 object to which you can call functions such as:

 transform = g.attr("transform"); 

Using

 d3.select(this.parentNode) 

will just return an SVG element. Below I tested various options.

 // Variant 1 circle = d3.select("#c1"); g = d3.select(circle.parentNode); d3.select("#t1").text("Variant 1: " + g); // This fails: //transform = d3.transform(g.attr("transform")); // Variant 2 circle = d3.select("#c1"); g = circle.node().parentNode; d3.select("#t2").text("Variant 2: " + g); // This fails: //transform = d3.transform(g.attr("transform")); // Variant 3 circle = d3.select("#c1"); g = circle.select(function() { return this.parentNode; }); transform = d3.transform(g.attr("transform")); d3.select("#t3").text("Variant 3: " + transform); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> <html> <body> <svg height="200" width="300"> <g> <circle id="c1" cx="50" cy="50" r="40" fill="green" /> </g> <text id="t1" x="0" y="120"></text> <text id="t2" x="0" y="140"></text> <text id="t3" x="0" y="160"></text> </svg> </body> </html> 
+4
May 03 '17 at 20:41
source share



All Articles