Get all dom nodes from d3 selection

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

EDIT Added code to help us.

  • Trying with each()is the only one that produces a query output, although quite verbose.
  • The call sel[0]also returns an array with DOM nodes, but it is hacked (depending on the internal structure of the library) and includes an undesired 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> 

// 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> (what I want)

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

// @thisOneGuy 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>
Run codeHide result

EDIT 2 Why do I want to do this?
To cause an array techniques , for example reduce, and mapto the DOM nodes. D3 provides filter, but to use others, I first need to extract the node array from the selection.

+4
1

, ...

, d3 v4 . , :

 d3.selection.prototype.nodes = function(){
   var nodes = new Array(this.size()), i = -1;
   this.each(function() { nodes[++i] = this; });
   return nodes;
 }

:

d3.selection.prototype.nodes = function(){
  var nodes = new Array(this.size()), i = -1;
  this.each(function() { nodes[++i] = this; });
  return nodes;
}


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.nodes());
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Hide result

@mbostock, - .

+6

All Articles