如何生成一个完全由DOM元素及其所有后代组成的d3选择? [英] How to generate a d3 selection consisting exactly of a DOM element and all its descendants?

查看:199
本文介绍了如何生成一个完全由DOM元素及其所有后代组成的d3选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设 X 是一些任意的DOM元素 1 。如何生成包含 X 及其所有后代的d3.js选择?

Suppose that X is some arbitrary DOM element1. How can I generate a d3.js selection containing exactly X and all its descendants?

(注意 d3.select(X).selectAll('*')给出的选择将包含 X ,但不会包含 X 本身。)

(Note that the selection given by d3.select(X).selectAll('*') will contain all the descendants of X, but it will not contain X itself.)

1 对于这个问题, X 的唯一约束是表达式 d3.select (X)评估为有效的d3.js选择。

1For this question, the only constraint on X is that the expression d3.select(X) evaluate to a valid d3.js selection.

推荐答案

a href =https://github.com/mbostock/d3/wiki/Selections#d3_selectAll =nofollow> d3.selectAll(nodes) 接受数组式对象作为参数,您可以获取 NodeList ,将其转换为数组并将您的节点x添加到它。将此数组传递到 d3.selectAll()将返回包含节点x及其所有后代的所需选择。

Since d3.selectAll(nodes) accepts an array-like object as a parameter you could obtain a NodeList of all descendants of your node x, convert it to an array and add your node x to it. Passing this array to d3.selectAll() will return the desired selection containing node x as well as all its descendants.

检查此操作 JSFiddle

var x = d3.select("#a_2").node(); // your node

// Get all children of node x as NodeList and convert to Array.
var xAndDescendants = Array.prototype.slice.call(  
        x.querySelectorAll("*")
    );  

// Add node x to the beginning
xAndDescendants.unshift(x);

// Select resulting array via d3.js
var selection = d3.selectAll(xAndDescendants);

这篇关于如何生成一个完全由DOM元素及其所有后代组成的d3选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆