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

和自甴很熟 提交于 2019-12-28 11:50:08

问题


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)?


回答1:


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").




回答2:


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>


来源:https://stackoverflow.com/questions/20641953/how-to-select-parent-element-of-current-element-in-d3-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!