Say I have an svg:
<svg>
  <text font-size="24" id="svg_1" y="63" x="69.5" stroke-width="0" stroke="#000" fill="#000000">1</text>
  <text font-size="24" id="svg_2" y="194" x="73.5" stroke-width="0" stroke="#000" fill="#000000">2</text>
  <text font-size="24" id="svg_3" y="313" x="60.5" stroke-width="0" stroke="#000" fill="#000000">3</text>
 </g>
</svg>
What argument to svg.selectAll() or svg.filter() can I use to select only the text node with value "2" and use .attr() to change its color?
I have found a lot of literature on selecting by attribute, but not by text value.
text() without arguments is a getter.
Thus, inside the filter function, this code:
d3.select(this).text() == 2
Will be evaluated as true for any <text> element with "2" as value.
Here is a demo:
d3.selectAll("text")
  .filter(function(){ 
    return d3.select(this).text() == 2
  })
  .attr("fill", "red");
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg>
    <text font-size="24" id="svg_1" y="20" x="20" stroke-width="0" stroke="#000" fill="#000000">1</text>
    <text font-size="24" id="svg_2" y="50" x="20" stroke-width="0" stroke="#000" fill="#000000">2</text>
    <text font-size="24" id="svg_3" y="80" x="20" stroke-width="0" stroke="#000" fill="#000000">3</text>
</svg>
PS: in D3, getters normally return a string. That's why I'm not using the strict equality operator (===). Check it:
var value = d3.select("#svg_2").text();
console.log("value is: " + value);
console.log("type is: " + typeof(value));
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg>
    <text font-size="24" id="svg_1" y="20" x="20" stroke-width="0" stroke="#000" fill="#000000">1</text>
    <text font-size="24" id="svg_2" y="50" x="20" stroke-width="0" stroke="#000" fill="#000000">2</text>
    <text font-size="24" id="svg_3" y="80" x="20" stroke-width="0" stroke="#000" fill="#000000">3</text>
</svg>
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