Reputation: 35301
Suppose that X
is some arbitrary DOM element1. How can I generate a d3.js selection containing exactly X
and all its descendants?
(Note that the selection given by d3.select(X).selectAll('*')
will contain all the descendants of X
, but it will not contain X
itself.)
1For this question, the only constraint on X
is that the expression d3.select(X)
evaluate to a valid d3.js selection.
Upvotes: 1
Views: 148
Reputation: 21578
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.
Check this working 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);
Upvotes: 2