Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access "previous sibling" of `this` when iterating over a selection?

Tags:

d3.js

In the following code, assume that $sel is some arbitrary d3.js selection:

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

What can I replace the ??? to assign to prev a d3.js selection consisting of the previous sibling of this (if any such exists)?

(If this is a first child, and therefore has no previous sibling, an empty d3.js selection should be assigned to prev.)

like image 916
kjo Avatar asked Apr 09 '15 14:04

kjo


People also ask

How do you get your old sibling element in react?

You can use previousElementSibling to get the previous element node (skipping text nodes and any other non-element nodes). To navigate the opposite way through the child nodes list use Node. nextSibling.

What is previousSibling?

previousSibling returns the previous node (an element node, a text node or a comment node). Whitespace between elements are also text nodes. previousElementSibling returns the previous element (not text and comment nodes).


1 Answers

It might be as simple as

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

If you are interested in element nodes only you would go for

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>
like image 155
altocumulus Avatar answered Oct 26 '22 05:10

altocumulus