title: How can I get a list of tree-ancestors and tree-descendants from this d3.js layout.tree?
body: <p>I'm experimenting with and modifying <a href="https://bl.ocks.org/mbostock/4339083" rel="nofollow noreferrer"><strong>this</strong></a> example of d3.js to draw a tree based on a JSON tree structure. This is what part of the tree looks like to start out with:</p>
  
  <p>I'm trying to make 2 separate modifications, but I don't know how to do them:</p>
  
  <ol>
  <li>When the text of a node is clicked, I want to get a collection of the text elements of all the tree-descendants. I want to do this so that I can toggle their style classes between <code>my-old-class</code> and <code>my-new-class</code>.</li>
  <li>When the text of a node is clicked, I want to get a collection of the text elements of all the tree-ancestors. I want to do this so that I can toggle their style classes between <code>my-old-class</code> and <code>my-new-class</code>.</li>
  </ol>
  
  <p>How can I do it?</p>
  
  <p>I don't know at all how to do #1 at all other than I need to add an on-click function to the <code>nodeEnter.append("text")</code> statement. But what should that function do?</p>
  
  <p>For #2, I know this is the relevant part of the code I need to modify. Something like this:</p>
  
  <pre><code>nodeEnter.append("text")
    .attr("x", function(d) { return d.children || d._children ? -10 : 10; })
    .attr("dy", ".35em")
    .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
    .text(function(d) { return d.name; })
    .style("fill-opacity", 1e-6)
    .on("click", function(d) {
          for (var currentAncestor = this.parentNode; /* WHAT EXPRESSION GOES HERE?? */; currentAncestor = currentAncestor.parentNode) {
              var ancestorText = /* WHAT EXPRESSION GOES HERE?? */;
              ancestorText.classed("my-new-class", !ancestorText.classed("my-new-class"));
              ancestorText.classed("my-old-class", !ancestorText.classed("my-old-class"));
    });
  </code></pre>
  
  <p>But I'm not sure what to put in place of those two expressions such that I properly loop through the text elements <strong>only</strong> of the tree's ancestors (not the DOM ancestors!!)</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>As an example, in the screenshot below, when the user clicks on the text "data", I want its ancestors text ("vis" and "flare") and its descendants text (every word that appears to the right of "data" to become red)</p>
  
  <p><a href="https://i.stack.imgur.com/XYqXn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XYqXn.png" alt="enter image description here"></a></p>