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

Javascriptd3.js

Javascript Problem Overview


I want to access the parent element of current element

Here is the structure of HTML

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 on hover of any particular circle

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

On hover I can select current element through d3.select(this),How can I get root element(g in my case)?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

To get the root element g (as cuckovic points out) can be got using:

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

This will return a d3 object on which you can call functions like:

transform = g.attr("transform");

Using

d3.select(this.parentNode)

will just return the SVG element. Below I have tested the different variants.

// 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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3074097View Question on Stackoverflow
Solution 1 - JavascriptcuckovicView Answer on Stackoverflow
Solution 2 - JavascriptMolossusView Answer on Stackoverflow