如何使用d3选择特定的父元素?

6

我想选择可能在几个层级之上的父节点。如何使用d3实现这一功能?

<div class="parent">
   <div class="stepson">
       <div class="child">
            Wassup Fatso?
       </div>
   </div>
</div>

d3.select('.child').parent('.parent')....? //I would like to go up the dom to a element with class parent.

CSS中没有父选择器(如果存在,您可以在d3.select中使用)。因此,最好的方法是创建自己的函数来遍历DOM。 - Gerardo Furtado
2个回答

7

找到匹配某个选择器字符串的父元素最简单的方法是使用Element.closest()方法:

Element本身开始,closest()方法遍历Element的父级(朝向文档根),直到找到与提供的selectorString匹配的节点。

为了将其限制在D3宇宙内,您可以利用selection.select()方法,该方法接受选择器函数作为其参数:

如果选择器是一个函数,则对每个选定的元素按顺序进行评估,传递当前数据(d)、当前索引(i)和当前组(nodes),其中this作为当前DOM元素(nodes[i])。它必须返回一个元素,如果没有匹配的元素则返回null。
在子元素的选择上调用此方法,您可以访问由this引用的子元素的DOM元素。从那里,您可以轻松找到您想要的父元素。
const parent = child.select(function() {
  return this.closest(".parent");  // Get the closest parent matching the selector string.
});

请查看以下代码片段以获取可执行演示:

const child = d3.select(".child");  // Select the child.

const parent = child.select(function() {
  return this.closest(".parent");   // Get the closest parent matching the selector string.
});

console.log(parent.node());         // <div class="parent">…</div>
<script src="https://d3js.org/d3.v5.js"></script>

<div class="parent">
   <div class="stepson">
       <div class="child">
            Wassup Fatso?
       </div>
   </div>
</div>


1
我认为D3没有提供类似于jQuery的选择器。您可能可以通过本地DOM选择器来实现。
var parent = d3.select('.child').node().parentNode.parentNode

然后,您可以这样检索此节点的数据。
d3.select(parent).datum()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接