kjo
kjo

Reputation: 35301

How to generate a d3 selection consisting exactly of a DOM element and all its descendants?

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

Answers (2)

altocumulus
altocumulus

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

Josh
Josh

Reputation: 5470

d3.selectAll("X, X *")

should work

Upvotes: 0

Related Questions