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
.)
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.
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).
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With