Get all dom nodes from d3 selection

Viewed 4881

selection.node() returns only the first node. Can we get an array of all nodes from a selection?

EDIT Added some code to help us.

  • The attempt with each() is the only one producing the wanted output, although quite verbose.
  • Calling sel[0] also returns an array with DOM nodes, but it's hacky (depends on the internal structure of the library) and includes an unwanted "parentNode" field.

// creating a selection to experiment with
var data= [1,2,3,4]
var sel = d3.select("li")
 .data(data)
 .enter().append("li").html(identity);
function identity(d){return d}
console.log(sel); // array[1] with array[4] with the <li>'s 

// using .node()
var res1 = sel.node();
console.log(res1); // first <li> only

// using .each() to accumulate nodes in an array
var res2 = [];
function appendToRes2(){
 res2.push(this);
}
sel.each(appendToRes2);
console.log(res2); // array[4] with the <li>'s (what I want)

// calling sel[0]
var res3 = sel[0];
console.log(res3); // array[4] with the <li>'s plus a "parentNode"

// @thisOneGuy's suggestion
var res4 = d3.selectAll(sel);
console.log(res4); // array[1] with array[1] with array[4] with the <li>'s
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

EDIT 2 Why do I want to do that?
To call array methods like reduce and map on the DOM nodes. D3 provides filter but to use others I first need to extract the node array from the selection.

1 Answers
Related