Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3 Selecting based on text value of node

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.

like image 303
Luke B Avatar asked Feb 28 '17 04:02

Luke B


1 Answers

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>
like image 191
Gerardo Furtado Avatar answered Oct 06 '22 12:10

Gerardo Furtado