How to access the `previous sibling`` this` when repeating a selection?

In the following code, suppose $sel is an arbitrary choice of d3.js:

 $sel.each(function(d, i, j) { var prev = ??? ; ... }); 

What can I replace ??? to assign the prev choice d3.js consisting of the previous brother to this (if one exists)?

(If this is the first child and therefore does not have a previous sibling, the empty choice d3.js should be assigned prev .)

+7
source share
1 answer

It can be as simple as

 var prev = d3.select(this.previousSibling); 

If you are only interested in element nodes, you can go to

 var prev = d3.select(this.previousElementSibling); 

 d3.selectAll(".c").each(function() { console.log(d3.select(this)); // Element <p class="c"></p> console.log(d3.select(this.previousSibling)); // text node containing whitespace between b and c console.log(d3.select(this.previousElementSibling)); // Element <p class="b"></p> }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> <div> <p class="a"></p> <p class="b"></p> <p class="c"></p> <p class="d"></p> <p class="e"></p> </div> 
+13
source share

All Articles