10

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.)

kjo
  • 33,683
  • 52
  • 148
  • 265
  • In general, you can't do that, because there's no selector for the previous sibling of something. It sounds like you'd be better off operating off the parent element though and selecting children as required. – Lars Kotthoff Apr 09 '15 at 15:15

1 Answers1

17

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>
altocumulus
  • 21,179
  • 13
  • 61
  • 84